kzrfaisal
kzrfaisal

Reputation: 1443

How to execute something after subscribe in angular

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

Upvotes: 13

Views: 42058

Answers (3)

seescode
seescode

Reputation: 2131

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

Upvotes: 4

icoum
icoum

Reputation: 221

seescode's answer helped me but I can't comment it.

I just wanted to say that with RxJS 6, their way to chain Observable operators changed, and we now have to use the pipe(...) method. (see RxJS 6 - What Changed? What's New?)

Here is what his InnerFunc would look like updated to RxJS 6 :

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

Upvotes: 3

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You could have finally event over observable, so that subscription got called.

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

Upvotes: 2

Related Questions