I've to observers the obser_user one will return the user_Id. Once I have the user Id I can create the obser_quests that gets the quests related to the user.

My issue here is that I can't create the obser_quests if I don't have the user_Id. Thus the only workaround is to nest the observer subscriptions, but this seems messy.

How can I fix it in clean way?

let obser_user:Observable<any> = this.userWebapiService.currentApplicationUserRead();
//Can't create the second observer, I need the user_Id from observer_first
// let obser_quests:Observable<any> = this.questWebapiService.countQuestsCreatedByUser(this.applicationUser_Id_current);


obser_user.subscribe(
  (resp: IApplicationUser_vmr)=>{
    console.log("ZR resp:", resp);
    this.applicationUser_Id_current = resp.id;

    //Nested observer created. Not good.
    let obser_quests:Observable<any> = this.questWebapiService.countQuestsCreatedByUser(this.applicationUser_Id_current);
    obser_quests.subscribe(
      (resp: number)=>{
        console.log("ZR resp:", resp);
        this.countQuestsCreatedByUser = resp;
        this.totalPages = resp;
      },
      (error:any)=>{
        console.log("ZR erros:", error);
      },
      ()=>{
        console.log("ZR oservable completed.");
    });  

  },
  (error:any)=>{
    console.log("ZR erros:", error);
  },
  ()=>{
    console.log("ZR oservable completed.");
});

2 Answers

1
AryanJ-NYC On Best Solutions
import { catchError, finalize, flatMap } from 'rxjs/operators';

const obser_user = this.userWebapiService.currentApplicationUserRead();
obser_user.pipe(
  flatMap(user => this.questWebapiService.countQuestsCreatedByUser(user.id)),
  catchError(err => {
    // this is how you should handle errors
    console.log("ZR erros:", error);
  }),
  finalize(() => {
    // this is your finally block
    console.log("ZR oservable completed.");
  }),
).subscribe((questionCount: number) => {
  console.log("ZR resp:", questionCount);
  this.countQuestsCreatedByUser = questionCount;
  this.totalPages = questionCount;
});

I hope this helps. I've added how you should truly handle errors and finally blocks using catchError and finalize, respectively. Good luck!

1
A.Winnen On

you'll need rxJs pipe operators. e.g. flatMap With flatMap, you can map one observable's result to another observable.

this.userWebapiService.currentApplicationUserRead().pipe(
    flatMap(user => this.questWebapiService.countQuestsCreatedByUser(user.id))
).subscribe(questsCount => {
// do something with questCount
});