Angular2 - nested http requests

感情迁移 提交于 2019-12-25 04:18:12

问题


I have some component code that looks like this:

private myThing: MyThing;

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

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;
             });
    });
}

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!


回答1:


Try 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;
         });
  });
}


来源:https://stackoverflow.com/questions/38712121/angular2-nested-http-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!