Parallel HTTP requests in Angular 4
This will map
locations array in array of Observables,
forkJoin
will emit value, when all responses are in place
Observable
.forkJoin(this.locations
.map((element) => this.weatherService.getWeather(element))
.subscribe((data) => console.log(data));
The issue is that using the function keyword instead of an arrow function, you are losing what this
means. Inside a function using the function keyword, this
refers to the function and not to your component class.
Modify to something like this:
this.locations.forEach(element => {
this.weatherService.getWeather(element).subscribe((data) => {
console.log(data);
});
});
Note: You could also consider using forkJoin
to wrap multiple observables.
You can find docs on it here: https://www.learnrxjs.io/operators/combination/forkjoin.html
But the example here may be more helpful: rxjs with multiple forkjoin when doing http requests
UPDATE: See improved docs here:
https://rxjs.dev/api/index/function/forkJoin