user3689167 user3689167 - 4 months ago 43
HTTP Question

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


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!

Answer

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