Search code examples
angularif-statementasynchronous

How to return in an Async Function in Angular?


I am getting an error when adding an if else condition inside the async function in Angular. I need to have a return to avoid the error in my async function

enter image description here

  asyncFunction: (value) => {
      if (value.includes('SAMPLESTRING')) {
        const getApplication = this.myService.getApplication({ id: value })
        .pipe(map(({ Application }) => Application))
        
      } else {
        const getApplication = this.myService.getApplication({ name: value })
        .pipe(map(({ Applications }) => Applications))
      }  

      return getApplication;
    }

Solution

  • As mentioned currently the getApplication variable is defined in the if and else block and you can't access it outside of the scope,

    you should declare the variable outside of the block scope.

    asyncFunction: (value) => {
      const getApplication: Observable<Application[]> = of([]); 
    
      if (value.includes('SAMPLESTRING')) {
        getApplication = this.myService.getApplication({ id: value })
          .pipe(map(({ Application }) => [Application]))    
      } else {
        getApplication = this.myService.getApplication({ name: value })
          .pipe(map(({ Applications }) => Applications))
      }
    
      return getApplication;
    }