Reputation: 2517
How to combine two responses in to an array in angular?
Following is making an http post requests to two endpoints. How can I combine both of them an provide a return value as an array?
Like this:
postCombined() {
return combineLatest([this.link1$, this.link2$])
.pipe(
mergeMap(([link1, link2]: [string, string]) => {
return [
this.http.post(link1, values1, { headers }),
this.http.post(link2, values2, { headers }),
];
})
)
.subscribe(console.log);
}
Is my implementation is correct? or do I need to use forkJoin?
Upvotes: 1
Views: 65
Reputation: 23654
forkJoin
seems the better option as it allows us to group multiple observables and execute them in parallel, then return only one observable.
mergeMap
maintains multiple active inner subscriptions at once, so it’s possible to create a memory leak through long-lived inner subscriptions.
postCombined() {
return combineLatest([this.link1$, this.link2$])
.pipe(
let http1$ = this.http.post(link1, values1, {
headers
}), http2$ = this.http.post(link2, values2, {
headers
})
forkJoin([https1$, http2$])
)
.subscribe(console.log);
}
Taken from this article
Upvotes: 1