Home > Enterprise >  How to map Observable.forkJoin() responses with corresponding requests
How to map Observable.forkJoin() responses with corresponding requests

Time:12-08

I have a pipe which utilizes the httpClient to give a response observable. I have list of request URLs. So, the code looks like this:

let observables = urls.map(url=>myPipe.transform(url));
forkJoin(observables).subscribe(results=>console.log(results));

I want to create a Map/Object which will map the request urls to their respective responses. Like:

{
   url1 : response1,
   url2 : response2
   ...
}

I want them to be available at once, so using forkJoin.

CodePudding user response:

I assume your pipe transforms url to http request, so

try this:

let observables = Object.fromEntries(urls.map(url=>[url, myPipe.transform(url)]));
forkJoin(observables).subscribe(results=>console.log(results));

at first we create an object {url: Observable}, and then with forkJoin we can do exactly what you asked

  • Related