Search code examples
angulartypescriptrxjssubscription

Angular dependent subscriptions using forkJoin with code block for modifying data


I have a subscription that depends on the result of a previous subscription. I am using forkJoin so I don't have to nest them:

this.service.service1().pipe(
    flatMap((res1) => this.service.service2(res1))
).subscribe((res2) => {
    // Do something with res2.
});

The issue is that I need to modify the data before I call subscription #2. I would like to be able to do something like this:

this.service.service1().pipe(
    flatMap((res1) => {
      // Modify res1 data here.
      // Make 2nd Api Call
      this.service.service2(res1)
    })
).subscribe((res2) => {
    // Do something with res2.
});

Do I need a different operator/syntax to achieve this or am I able to modify this approach?


Solution

  • You were not returning an observable from your flatMap, return this.service.service2(res1); would do the same as below.

    this.service.service1().pipe(
        map(res1 => //modify resp1 here)
        flatMap((modifiedRes1) => this.service.service2(modifiedRes1)) // note the lack of brackets, this means we are returning the observable, your function returns void.
    ).subscribe((res2) => {
        // Do something with res2.
    });
    

    The difference between

    (res1) => this.service.service2(res1)
    

    and

    (res1) => {
      this.service.service2(res1)
    }
    

    Is that the first function returns an observable, the second one returns void.

    (res1) => this.service.service2(res1)
    

    and

    (res1) => {
      return this.service.service2(res1)
    }
    

    are equivalent. {} creates a block, that block needs a return statement if it is use in an arrow function.