How to accomplish something after signing in angular

I want to return a boolean, but the variable in the if condition is not defined.

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;
    }
}
+5
source share
3 answers

After you start using observables, you will have to work in a chain of methods with observables. In your case, you can 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);
  });    
}
+3
source

The answer with the code sees me, but I can not comment on it.

I just wanted to say that in RxJS 6 their path to the chain of observable operators has changed, and now we must use the pipe (...) method. (see RxJS 6 - What Has Changed? What's New? )

InnerFunc, RxJS 6:

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

You could have an event event observableto subscriptionreceive a call.

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

Source: https://habr.com/ru/post/1680889/


All Articles