Angular 4中的并行HTTP请求 [英] Parallel HTTP requests in Angular 4
问题描述
我正在构建一个简单的气象应用程序,该应用程序使用REST服务来显示用户输入的任何城市中的当前天气数据.
I am building a simple weather app that uses a REST service to display current weather data in any city entered by the user.
信息中心页面应显示用户指定的〜5个城市的当前天气.
The dashboard page should display the current weather in ~5 cities specified by the user.
所以我的问题是-给定一个由5个城市组成的数组,对该数组中的每个元素发出对REST服务(通过Angular服务)的调用的最佳方法是什么.
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):属性"weatherService"在"void"类型上不存在.
c:/Projects/weather-app/src/app/components/dashboard/dashboard.component.ts (19,12): Property 'weatherService' does not exist on type 'void'.
我意识到'forEach'在这里不起作用-但是在ng 4中执行此操作的最佳实践是什么?
I realize the 'forEach' is not going to work here - but what's the best practice for doing this in ng 4?
谢谢.
推荐答案
这将map
个可观察对象数组中的位置数组,
当所有响应都准备就绪时,forkJoin
将发出值
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));
这篇关于Angular 4中的并行HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!