angularangular-ui-routerngrx-storengrx-store-4.0angular-ngrx-data

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


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;
    }

Solution

  • 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));