Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 227
kzrfaisal Avatar asked Jul 06 '17 13:07

kzrfaisal


People also ask

What happens when you subscribe to an observable?

An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Returns an Observable instance that synchronously delivers the values provided as arguments.

Why do we use subscribe in Angular?

Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.


1 Answers

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;
      }
    )
  )
}
like image 102
icoum Avatar answered Oct 09 '22 03:10

icoum