Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel HTTP requests in Angular 4

I am building a simple weather app that uses a REST service to display current weather data in any city entered by the user.

The dashboard page should display the current weather in ~5 cities specified by the user.

So my question is - given an array of 5 cities, what is the best way to issue a call to the REST service (via Angular service) for each element in that array.

Here's a code excerpt from my initial attempt:

locations: string[] = ["Seattle", "Woodinville", "Krasnoyarsk", "Stockholm", "Beijing"];

...

ngOnInit() {

    this.locations.forEach(function(element) {
      this.weatherService.getWeather(element).subscribe((data) => {
        console.log(data);
      });
    });

  }

But this yields an error: Failed to compile.

c:/Projects/weather-app/src/app/components/dashboard/dashboard.component.ts (19,12): Property 'weatherService' does not exist on type 'void'.

I realize the 'forEach' is not going to work here - but what's the best practice for doing this in ng 4?

Thanks.

like image 294
jspru Avatar asked Sep 15 '17 21:09

jspru


People also ask

How do I stop multiple API calls?

On clicking on tabs you interchange state and you use ngOnInit() method every time when a state is changed to get the data.In this way, you can reduce API calls by using nested routing.

What is ForkJoin in Angular 8?

forkJoin is an operator that takes any number of input observables which can be passed either as an array or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed), then the resulting stream will complete immediately.


1 Answers

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));
like image 112
valorkin Avatar answered Sep 17 '22 17:09

valorkin