Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling two services one after another in Angular using Observables

I am attempting to call two services on the ngOnInit in Angular I have the following code:

.ts file

ngOnInit() {
    // Calling 1st service
    this.serviceOne.getAllServiceOneData().subscribe(
      data => (
        this.serviceOneData = data,
        console.log('successfully loaded all service one data')
      ),
      error => this.errorMessage =   error as any,
    );

    //Trying to call 2nd service
    if (this.serviceOneData.length > 0) {
      this.serviceOneData.forEach(so => {
        this.serviceTwo.getAllServiceTwoData(so.id.toString()).subscribe(
          data => (
            this.serviceTwoData= data,
            console.log('successfully loaded service two related data')
          ),
          error => this.errorMessage =   error as any,
        );
      });  //forEach
    }  //if
}

Now, I would like to subscribe to a second service and fetch the related information for each one of the items that was fetch on the first service.

Is that possible using observable in Angular? Btw, I am working with Angular 7.

like image 380
MikePR Avatar asked Oct 22 '25 03:10

MikePR


1 Answers

You should use switchMap and forkJoin like this (see the comments for the explanation):

this.serviceOne.getAllServiceOneData()
        .pipe(
          //Use switchMap to call another API(s)
          switchMap((dataFromServiceOne) => {
            //Lets map so to an observable of API call
            const allObs$ = dataFromServiceOne.map(so => this.serviceTwo.getAllServiceTwoData(so.id.toString()));

            //forkJoin will wait for the response to come for all of the observables
            return forkJoin(allObs$);
          })
        ).subscribe((forkJoinResponse) => {
          //forkJoinResponse will be an array of responses for each of the this.serviceTwo.getAllServiceTwoData CALL
          //Do whatever you want to do with this array
          console.log(forkJoinResponse);
        });

Instead of forkJoin you can also use concat depends on your app need.

Hope it helps.

like image 110
user2216584 Avatar answered Oct 23 '25 17:10

user2216584



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!