我正在从 Angular 4 代码调用网络服务并订阅响应。当响应到来时,我需要解析它并使用解析的信息调用另一个 web 服务(然后再次订阅响应)。
如何使用 Rxjs 订阅实现这种链接。
在下面的代码中,我调用客户网络服务来获取他的个人识别码。当我得到它时,只有到那时我才需要使用 pin 码作为输入来调用第二个休息服务。
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)
)
}
这是链接订阅的正确方式吗?在第二个服务的结果返回后,我需要再做一个网络服务。它会进一步嵌套代码块。
最佳答案
使用 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
关于Angular 4 - 链接订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44695221/