我正在构建一个简单的天气应用程序,它使用 REST 服务显示用户输入的任何城市的当前天气数据。
仪表板页面应显示用户指定的约 5 个城市的当前天气。
所以我的问题是 - 给定一个包含 5 个城市的数组,为该数组中的每个元素发出对 REST 服务的调用(通过 Angular 服务)的最佳方法是什么。
这是我最初尝试的代码摘录:
locations: string[] = ["Seattle", "Woodinville", "Krasnoyarsk", "Stockholm", "Beijing"];
...
ngOnInit() {
this.locations.forEach(function(element) {
this.weatherService.getWeather(element).subscribe((data) => {
console.log(data);
});
});
}
但这会产生一个错误: 编译失败。
c:/Projects/weather-app/src/app/components/dashboard/dashboard.component.ts (19,12): 类型“void”上不存在属性“weatherService”。
我知道 'forEach' 在这里不起作用 - 但在 ng 4 中执行此操作的最佳实践是什么?
谢谢。
最佳答案
这将在 Observables 数组中 map
locations 数组,
forkJoin
将在所有响应都到位时发出值
Observable
.forkJoin(this.locations
.map((element) => this.weatherService.getWeather(element))
.subscribe((data) => console.log(data));
关于angular - Angular 4 中的并行 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46247498/