jsp*_*pru 5 rest service http angular
我正在构建一个使用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);
});
});
}Run Code Online (Sandbox Code Playgroud)
但这会产生一个错误:编译失败。
c:/Projects/weather-app/src/app/components/dashboard/dashboard.component.ts(19,12):属性“ weatherService”在“ void”类型上不存在。
我意识到“ forEach”在这里不起作用-但是在ng 4中执行此操作的最佳实践是什么?
谢谢。
小智 8
当所有响应都到位后,这将map在Observables数组中定位location数组,
forkJoin并发出值
Observable
.forkJoin(this.locations
.map((element) => this.weatherService.getWeather(element))
.subscribe((data) => console.log(data));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3048 次 |
| 最近记录: |