1

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;
    }
Naga Raj
  • 19
  • 5
  • Can you try to re-phrase your question? Not sure what part of your code is supposed to return true. – gerstams Aug 11 '21 at 19:02

1 Answers1

1

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));
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25