SO I love forkJoin, basically the replacement of Promise.all, but I can't figure how to feed it a dynamic list as in:
Observable.forkJoin(
this.http.get('/app/books.json').map((res:Response) => res.json()),
this.http.get('/app/movies.json').map((res:Response) => res.json())
).subscribe(
data => {
this.books = data[0]
this.movies = data[1]
},
err => console.error(err)
);
only that I need to create the http.gets at runtime (the URLs will be different, destinations and total URLs generated all will be dynamic), tried to pass a config object but it didn't like it...
tx for reading,
Sean.
forkJoin takes first argument as
args (Arguments | Array): An array or arguments of Observable sequences or Promises to collect the last elements for.
So, you can simply pass it an array of observables . Here is a plunker
let observables = [
this.http.get('/app/books.json').map((res:Response) => res.json()),
this.http.get('/app/movies.json').map((res:Response) => res.json())
];
Observable.forkJoin(observables).subscribe(
data => {
this.books = data[0]
this.movies = data[1]
},
err => console.error(err)
);
I landed here looking for a way to identify the results of a dynamically assembled group of observables. If I pass an array of observables, I can't know which result will be at which index because the number of and order of observables in the array is unknown.
Since RxJS 6.5+, you can pass an object instead of an array into ForkJoin, where the key will identify the observable, and the value of the key is the observable (known as a dictionary).
// use some logic to dynamically assemble dictionary
const dictionary = {};
if (shouldGetBooks) {
dictionary.books = this.http.get("/app/books.json");
}
if (shouldGetMovies) {
dictionary.movies = this.http.get("/app/movies.json");
}
forkJoin(dictionary).subscribe((results) => {
console.log(results); // { books: booksJson, movies: moviesJson }
});
Now the results are easily identifiable by key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With