【问题标题】:Angular 4 - chaining subscribeAngular 4 - 链接订阅
【发布时间】:2017-11-25 11:40:35
【问题描述】:

我正在从 Angular 4 代码调用 Web 服务并订阅响应。当响应到来时,我需要解析它并使用解析的信息调用另一个 Web 服务(然后再次订阅响应)。

如何使用 Rxjs subscribe 实现这种链接。

在下面的代码中,我正在调用客户网络服务来获取他的密码。当我得到它时,我才需要使用密码作为输入调用第二个休息服务。

fetchCoordinates() {

    this.myService.get('http://<server>:<port>/customer')
      .subscribe(
      (response: Response) => {

        let pinUrl = JSON.parse(response.text()).items[0].pin;
        // Take the output from first rest call, and pass it to the second call
        this.myService.get(pinUrl).subscribe(
          (response: Response) => {
             console.log(response.text()); 
          }
        )
      },
      (error) => console.log('Error ' + error)
      )
  }

这是链接订阅的正确方式吗?在第二次服务的结果回来后,我需要再做一项网络服务。它会进一步嵌套代码块。

【问题讨论】:

  • 你做得对!有什么问题?
  • 想检查这是否是正确的方法,因为它会创建嵌套代码块。更新了问题以反映这一点。

标签: angular rxjs


【解决方案1】:

使用flatMap 会更简洁,因此只有一个订阅:

this.myService.get('http://<server>:<port>/customer')
.flatMap((response: Response) => { 
    let pinUrl = JSON.parse(response.text()).items[0].pin;
    return this.myService.get(pinUrl);
})
.subscribe((response: Response) => {
    console.log(response.text()); 
});

要了解 flatMap 的真正作用,请查看以下内容:https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

【讨论】:

  • 稍微解释一下flatMap或提供有用的链接,以便它可以帮助正在寻找这种解决方案的人。
猜你喜欢
  • 2018-05-25
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 2018-11-23
  • 2018-11-26
  • 1970-01-01
  • 2020-10-11
  • 2018-02-15
相关资源
最近更新 更多