作者:E阳光男孩 | 来源:互联网 | 2023-01-31 15:36
我从Angular 4代码调用web服务并订阅响应.当响应到来时,我需要解析它并使用解析的信息调用另一个webservice(然后再次订阅响应).
如何使用Rxjs订阅实现此链接.
在下面的代码中,我正在调用客户Web服务来获取他的密码.当我得到它时,我才需要用pin码作为输入来调用第二个休息服务.
fetchCoordinates() {
this.myService.get('http://:/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)
)
}
这是链接订阅的正确方法吗?在第二次服务的结果回来后,我需要再做一次网络服务.它将进一步嵌套代码块.
1> Faly..:
这将是更清洁使用flatMap
所以只有一个订阅:
this.myService.get('http://:/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`或提供有用的链接,以便它可以帮助那些正在寻找这种解决方案的人.