【发布时间】:2017-09-15 21:08:25
【问题描述】:
我正在构建一个简单的天气应用程序,它使用 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 中执行此操作的最佳做法是什么?
谢谢。
【问题讨论】: