Angular2 - 嵌套的http请求
Angular2 - nested http requests
我有一些组件代码如下所示:
private myThing: MyThing;
ngOnInit() {
this.service.getMyThing().subscribe(thing => {
this.myThing = thing;
}
}
但是,该服务看起来像这样 - 它由两个 http 请求连接的数据组成。第一个来自 "otherService",它为事物对象获取额外的 属性,第二个调用获取基础事物对象。我想合并这些结果并在所有操作完成后提醒订阅者,即 this.myThing 应该有“.prop” 属性...
public getMyThing(): Observable<MyThing> {
this.otherService.getThingProperty().subscribe(prop => {
return this.http.get('url')
.map(res => res.json())
.map(thing => {
thing.prop = prop;
});
});
}
但这显然是错误的——函数认为它是无效的,这是有道理的……我只是不知道如何让组件订阅最终的可观察对象。任何提示表示赞赏。谢谢!
尝试 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;
});
});
}
我有一些组件代码如下所示:
private myThing: MyThing;
ngOnInit() {
this.service.getMyThing().subscribe(thing => {
this.myThing = thing;
}
}
但是,该服务看起来像这样 - 它由两个 http 请求连接的数据组成。第一个来自 "otherService",它为事物对象获取额外的 属性,第二个调用获取基础事物对象。我想合并这些结果并在所有操作完成后提醒订阅者,即 this.myThing 应该有“.prop” 属性...
public getMyThing(): Observable<MyThing> {
this.otherService.getThingProperty().subscribe(prop => {
return this.http.get('url')
.map(res => res.json())
.map(thing => {
thing.prop = prop;
});
});
}
但这显然是错误的——函数认为它是无效的,这是有道理的……我只是不知道如何让组件订阅最终的可观察对象。任何提示表示赞赏。谢谢!
尝试 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;
});
});
}