2016-08-02 151 views
0

我有一些组件代码看起来像这样:Angular2 - 嵌套HTTP请求

private myThing: MyThing; 

ngOnInit() { 
    this.service.getMyThing().subscribe(thing => { 
     this.myThing = thing; 
    } 
} 

但是,该服务是这样的 - 它是由两个HTTP请求连接的数据的。第一个来自“otherService”,它为thing对象获取一个附加属性,第二个调用获取基础对象。我想结合这些结果,并提醒用户在所有已经完成的动作,即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; 
      }); 
    }); 
} 

但是,这显然是错误的 - 功能认为它是无效的,这是有道理的...我只是不知道如何让组件订阅最终的可观察。任何提示都表示赞赏。谢谢!

回答

1

尝试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; 
     }); 
    }); 
} 
+0

的switchmap看起来是正是我一直在寻找的......我意识到我缺少一块到我的拼图 - 你有没有这个问题的任何见解:HTTP:/ /stackoverflow.com/questions/38712303/angular2-return-observable-of-object-created-in-map-function – user3689167

+0

'switchMap' FTW !!! – Matt