Angular2 - 嵌套的http请求 [英] Angular2 - nested http requests
问题描述
我有一些组件代码如下所示:
I have some component code that looks like this:
private myThing: MyThing;
ngOnInit() {
this.service.getMyThing().subscribe(thing => {
this.myThing = thing;
}
}
但是,服务看起来像这样 - 它由两个http请求加入的数据组成。第一个来自otherService,它为thing对象获取一个额外的属性,第二个调用获取基础的东西对象。我想结合这些结果并在所有动作完成后提醒用户,即this.myThing应该有。prop属性......
However, the service looks like this - it is composed of data joined by two http requests. The first one is from "otherService", which fetches an additional property for the thing object, and the second call fetches the base thing object. I would like to combine these results and alert the subscriber when all action has been completed, i.e. this.myThing should have the ".prop" property...
public getMyThing(): Observable<MyThing> {
this.otherService.getThingProperty().subscribe(prop => {
return this.http.get('url')
.map(res => res.json())
.map(thing => {
thing.prop = prop;
});
});
}
但这显然是错误的 - 该函数认为它是有意义的无效......我只是不知道如何让组件订阅最终的observable。任何提示都表示赞赏。谢谢!
But this is clearly wrong - the function thinks it is void which makes sense... I just don't know how to get the component to subscribe to the final observable. Any tips are appreciated. Thanks!
推荐答案
尝试 switchMap
:
public getMyThing(): Observable<MyThing> {
return this.otherService.getThingProperty().switchMap(prop => {
return this.http.get('url')
.map(res => res.json())
.map(thing => {
thing.prop = prop;
});
});
}
这篇关于Angular2 - 嵌套的http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!