2
votes

I am trying to return a boolean observable from a response that I get from an observable that is inside a response from a parent observable. But the child observable will not always run depending on the res from the parent observable.

I know to make this work I have to use .map and I can return the observable in the subscribe but after that I am stumped.

the scenario is that I do an auth check if that passes then do the api call if it fails return false. If the api call fails return false and if it succeeds return true.

    getEvents(): Observable<boolean> {
       this.authSrvc.authCheck().map((res: boolean) => {
          if (res) {
                this.eventsSrvc.getEvents(this.pageNum, this.pageSize, this.searchText).timeout(15000).map((data: Response) => data.json()).subscribe((res:any)=>
                {
                    if(res.value.length === 0)
                    {
                        Observable.of(false);
                    }
                    else
                    {
this.eventsList = this.eventsList.concat(data);

                        this.storage.ready().then(() => {
                            this.storage.set('events', this.eventsList)
                        })
                        Observable.of(true);


                    }
                },(err:any)=>
                {

                    this.helperSrvc.errorMessage(err);
  return Observable.of(false);
                })
            }
            else {
this.helperSrvc.authFailed();
                this.authSrvc.logout();
                this.pushSrvc.unRegisterPush();
                this.calendarSrvc.clearEvents();
                this.locationSrvc.clearGeofences();
                this.navCtrl.setRoot(AuthPage);
                return Observable.of(false);
               // 
            }
        })
    }

I either cant get the response or I get told that the function that calls this doesnt have .subscribe() available.

1

1 Answers

3
votes

I think you need to use flatMap, I have changed your code below.

getEvents(): Observable<boolean> {
return this.authSrvc.authCheck().flatMap((res: boolean) => {
  if (res) {
    return this.eventsSrvc.getEvents(this.pageNum, this.pageSize, this.searchText)
    .timeout(15000)
    .map((data: Response) => data.json())
    .flatMap((res: any) => {
      if (res.value.length === 0) {
        return Observable.of(false);
      }
      else {
        this.eventsList = this.eventsList.concat(data);

        this.storage.ready().then(() => {
          this.storage.set('events', this.eventsList);
        });
        return Observable.of(true);
      }
    });
  }
  else {
    return Observable.of(false);
    // 
  }
})
}

EDIT: I removed your error handler, you need to pass it when you subscribe to getEvents.

getEvents().subscribe(
   (res:boolen) => {},
   (err:any)=>{
      this.helperSrvc.errorMessage(err);
   }
);