12

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;
    }
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
kzrfaisal
  • 1,355
  • 5
  • 15
  • 26

3 Answers3

4

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);
  });    
}
seescode
  • 2,101
  • 15
  • 31
3

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;
      }
    )
  )
}
icoum
  • 171
  • 1
  • 5
2

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);
});
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • 2
    why not use the third callback of `subscribe` ? – Dhyey Jul 06 '17 at 13:38
  • 1
    in finally ..it's coming undefined – kzrfaisal Jul 06 '17 at 13:42
  • Actually I want to work on the data recieved in subscribe ,based on that data i want to return a boolean value, I can't do this whole code in subscribe beacause value will not be reflected from subscribe – kzrfaisal Jul 06 '17 at 13:46
  • @MohdFaisalAnsari finally well get called after each stream event gets received/rejected, what exactly you needed? – Pankaj Parkar Jul 06 '17 at 15:18
  • @Dhyey I assumed `finally` and `3rd` subscribe callback does the same thing, so using `finally` make it more readable IMO;) – Pankaj Parkar Jul 06 '17 at 16:36
  • @PankajParker shouldn't you use fat arrow functions as value of `this` will change when a function is defined with `function` keyword. @MohdFaisalAnsari u should try `finally(() => console.log(this.mainMenus) ) ` – Dhyey Jul 07 '17 at 02:33