Reputation: 734
Note. I am restricted to Angular
and RxJS
version 5. :-(
I would like to call a API a number of times depending on the values in an Array that comes from an observable that I am already subscribed to. The code follows this logic:
this.api.doSomething()
.pipe(
tap(things => this.thingsArray = things),
// I want to call an API like this:
for(const thing of things) {
this.secondApi.getOtherThings(thing.id)
.pipe(
tap(otherthing => this.ExtendedThings.push ({...request, otherThingy: otherThing)
)
}
).subscribe()
I am interested in how can I do this on the front-end. I have tried concat
but does not have any subscribe
methods in the way I did it. I guess I was doing it wrong. Any help would be greatly appreciated.
Upvotes: 0
Views: 271
Reputation: 1844
I think this may be what you want. Flatmap allows you to use the result of one Observable to make another request. In this case, we will return an observable made by merging multiple observables.
this.api.doSomething()
.pipe(
tap(things => this.thingsArray = things),
flatMap(
// an array containing all observables with the second set of requests
const secondaryRequests = things.map(thing=>{
return this.secondApi.getOtherThings(thing.id)
})
// creates an observable that combines all observables in the array.
// merge would work similarly
return concat(secondaryRequests)
),
// otherthing is the result of the second requests (one at a time)
tap(otherthing => this.ExtendedThings.push ({...request, otherThingy: otherThing})),
).subscribe()
Upvotes: 1