I have a service and its getAllMessages()
returns an observable of an array of items : Observable<ITEM[]>
I map the result like this to post each ITEM to a RestAPI :
this.service.getAllMessages()
.map(items => ...for each item of items, call this.apiService.postMessage(item)...)
postMessage(item)
returns an Observable<Response>
My goal is to get an Observable<Response[]>
for which I can check the http code of every post from this.apiService.postMessage(item)
I tried using flatMap
:
this.service.getAllMessages()
.flatMap(items => {
return items.map(item => {
return this.apiService.postMessage(item);
});
}).subscribe(RES => {
console.log(RES);
});
but here RES is an Observable<Response>
and not a simple Response
How can I achieve this ?
What is returned by your this.service.getAllMessages()
is an array of Observable
, not an Observable
of array. The .map()
function belongs to the function of array.
If you want to execute all the Observables in parallel, use .forkJoin()
:
this.service.getAllMessages()
.flatMap(items => {
return Observable.forkJoin(items.map(item => this.apiService.postMessage(item)));
})
.subscribe(RES => {
console.log(RES);
});
If you want to execute the observables in sequential, use .concat()
:
this.service.getAllMessages()
.flatMap(items => {
return Observable.concat(...items.map(item => this.apiService.postMessage(item)));
})
.subscribe(RES => {
console.log(RES);
});
Note the spread operator for .concat
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments