Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Observable<Object> to Observable<Array<Object>>

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading