2016-08-02 112 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