Home > other >  Observable<Object> to Observable<Array<Object>>
Observable<Object> to Observable<Array<Object>>

Time:10-25

I have HttpClient.post request. I pass id in the body and it returns Observable< Object >. It works fine.

let obj: Observable<Object> = []
let IDs = [1, 2, 3]
for (const id of IDs) {
    obj.push(httpClient.post('/api/object', { id: id })
  }

But I need to call it many times with different id. How can I rewrite my code to return Observable< Array< Object > > for the same API ?

CodePudding user response:

You should use forkJoin operator from 'rxjs' in order to achieve this. You can pass in an array of HttpClient.post observables and it will return an Observable of an array of result objects, once all calls have completed.

Here is a code example:

const ids = [1, 2, 3, 4];

const result$ = forkJoin(
  ids.map((id) => this.http.post<Result>(`yoururl/objects/${id}`, {}))
);

In this case result$ will be an observable that emits one array of type Result once all post requests have completed.

  • Related