angular - Angular 4 中的并行 HTTP 请求

标签 angular rest http service

我正在构建一个简单的天气应用程序,它使用 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/

相关文章:

Angular 2 RxJS 可观察到的 : RetryWhen filter retry on error Status

forms - 输入时没有表单标签的表单验证 - Angular 2

javascript - 使用 Router 将对象传递给 Angular2 组件

ruby - 如何在 Rails 中发出异步 http 请求

iOS:NSURLConnection sendAsynchronousRequest 对 NSImageView 的延迟操作

javascript - 如何在 Angular $http 响应中捕获格式错误的 JSON?

c# - ASP.NET Core CORS WebAPI : no Access-Control-Allow-Origin header

java - 我的 REST 方法应该有一个单独的 Controller 吗?

javascript - 使用 REST API 从本地主机进行开发时处理 CORS - Streamlabs API

MySql 和 Glassfish : Error in allocating a connection