Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading