Angular 4-链接订阅 [英] Angular 4 - chaining subscribe

查看:79
本文介绍了Angular 4-链接订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am calling a webservice from Angular 4 code and subscribing to the response. When the response comes, I need to parse it and using the parsed information call another webservice (and then subscribe to the response once again).

如何使用Rxjs订阅实现此链接.

How can I achieve this chaining using Rxjs subscribe.

在下面的代码中,我正在调用客户Web服务以获取他的个人识别码.当我知道了这一点后,我才需要使用PIN码作为输入来调用第二休息服务.

In the below code, I am calling a customer web service to get his pin code. When I get that, only then I need to call the 2nd rest service with pin code as an input.

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)
      )
  }

这是链接订阅的正确方法吗?在第二个服务的结果返回后,我需要再做一个Web服务.它将进一步嵌套代码块.

Is this the right way of chaining subscribe? I need to do one more web service after results of 2nd services comes back. It would be nesting the code block even further.

推荐答案

使用 flatMap 可以更清洁,因此只有一个订阅:

This will be cleaner with the use of flatMap so there is just one subscribe:

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 的实际功能,请看以下内容:

To understand what flatMap really does, take a look at this: https://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

这篇关于Angular 4-链接订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆