Angular 4 – 链接订阅
发布时间:2020-12-17 17:33:23 所属栏目:安全 来源:网络整理
导读:我从Angular 4代码调用web服务并订阅响应.当响应到来时,我需要解析它并使用解析的信息调用另一个webservice(然后再次订阅响应). 如何使用Rxjs订阅实现此链接. 在下面的代码中,我正在调用客户Web服务来获取他的密码.当我得到它时,我才需要用pin码作为输入来调
我从Angular 4代码调用web服务并订阅响应.当响应到来时,我需要解析它并使用解析的信息调用另一个webservice(然后再次订阅响应).
如何使用Rxjs订阅实现此链接. 在下面的代码中,我正在调用客户Web服务来获取他的密码.当我得到它时,我才需要用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |