0

Hi all In my angular app I have two methods getA and getB. I've added third one getC that is dependent on results from getB. How can I wait for getB to complete ? I want to use this.B variable in getC method.

 async ngOnInit() {
      await getA();
      await getB();
      await getC();
 }

getA(): void {
  this.service.fetchA(this.id)
     .pipe(takeUntil(this.ngUnsubscribe))
        .subscribe((res) => {
            {
                this.A = res;
            }
        });

}

getB(): void {
  this.service.fetchB(this.id)
       .pipe(takeUntil(this.ngUnsubscribe))
           .subscribe((res) => {
              this.B = res;
           });
}

getC(): void{
  this.service.fetchC(this.id).subscribe((res) => {
      this.C = this.B + something;
   });
}

2 Answers2

0

You could do something like this.

async ngOnInit() {
      getA();
      getB();
 }

getA()....

getB(): void {
  this.service.fetchB(this.id)
       .pipe(takeUntil(this.ngUnsubscribe))
           .subscribe((res) => {
              this.B = res;
              this.getC();
           });
}

getC()....
jna
  • 926
  • 10
  • 18
0

It is hard to tell how your services work. If these are http requests you do not need unsubscribe. If A is irrelevant, then simple switchMap will do the trick:

this.service.fetchB().pipe(
  switchMap((serviceBresult:resultBtype) => 
    this.service.fetchC(serviceBresult)
  ),
  tap((serviceCResult:'resultCtype') => console.log(serviceCResult))
).subscribe()
rood
  • 11,073
  • 3
  • 19
  • 18