Not returning the true value from subscriber after execution its always returning default value false

103 Views Asked by At

While prefillLoginId is executing, I'm always getting false (default value), even though for each code inside the subscription is executing. Please help me out to return True value.

private prefillLoginId(currentLoginId: any, cms: any) 
    {
        let status =false;
        let patterns = [];            
        this.subSink.sink = cms.subscribe(content => {           
           
           patterns = !!content['ClientSideValidations']['LoginId'] ? content['ClientSideValidations']['LoginId'] : [''];          
           status = this.patternCheckStatus(patterns, currentLoginId);;
           });           
        return status;
    }

   private patternCheckStatus(patterns:any,currentLoginId)
    {
        let patternCheckStatus = false;
        let regex: RegExp;
        patterns.forEach(x => {
            regex = new RegExp(x);   
             if (regex.test(currentLoginId)) {                              
              patternCheckStatus = true;
             }
            });
            
            
            return patternCheckStatus;
    }
1

There are 1 best solutions below

0
Aakash Garg On BEST ANSWER

This is because of async operation here. the code inside subscribe executes after returning status from your method and when it was returning its value was false. you should change your method to return observable like below :-

private prefillLoginId(currentLoginId: any, cms: any) 
    {
        let status =false;
        let patterns = [];            
        return cms.pipe(map(content => {           
           
           patterns = !!content['ClientSideValidations']['LoginId'] ? content['ClientSideValidations']['LoginId'] : [''];          
           status = this.patternCheckStatus(patterns, currentLoginId);;
           return status;
        }));           
    }

and where ever you call this method use it like :-

prefillLoginId.subscribe((status) => console.log(status));