How to execute something after subscribe in angular

kzrfaisal picture kzrfaisal · Jul 6, 2017 · Viewed 25.7k times · Source

I want to return a boolean value ,but the variable in the "if" condition is undefined.

function() {
    this.menuDataService.getMenu()
      .subscribe(res => {
       this.mainMenus = res.MainMenus;
       console.log(this.mainMenus);
    });

    console.log(this.mainMenus);

    if(this.mainMenus == 1){
       return true;
    }
    else {
      return false;
    }
}

Answer

seescode picture seescode · Jul 8, 2017

Once you start using observables you have to work within the chained set of methods off of the observable. In your case you could do something like this:

function InnerFunc(){
  return this.menuDataService.getMenu()
  .map(res => {
    if(res.mainMenus == 1){
     return true;
    }
    else{
     return false;
    }
  )
}

function OuterFunc() {
  InnerFunc()
  .subscribe(result =>{
      // will be either true or false
      console.log(result);
  });    
}