4

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 ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot you saved my day ! (didnt know about the spread operator, happy to learn)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.