2016-12-06 63 views
0

返回下面這個問題:Add data to http response using rxjsRxjs:將數據添加到數組中的元素,從HTTP響應

我試過這個代碼適應了上述第一HTTP調用的結果生成一個數組,而不是我的使用情況價值......但我無法理解它。 如何在rxjs(Typescript)中編寫以下僞代碼?

叫我的服務器

獲得對象的數組具有下列性質:(外部ID,名稱)

對於每個對象,調用另一服務器傳遞所述外部ID

用於從每個響應外部服務器,獲取另一個對象,並將其一些屬性合併到我的服務器的對象中,並使用相同的ID

最後,訂閱並獲取具有以下結構的增強對象數組: (外部ID,姓名,增強爲prop1,增強PROP2,...)

到目前爲止,我能夠做的唯一事情就是:提前

this._appService 
     .getUserGames() 
     .subscribe(games => { 
      this._userGames = _.map(games, game => ({ id: game.id, externalGameId: game.externalGameId, name: game.name })); 
      _.forEach(this._userGames, game => { 
       this._externalService 
        .getExternalGameById(game.externalGameId) 
        .subscribe(externalThing => { 
         (<any>game).thumbnail = externalThing.thumbnail; 
         (<any>game).name = externalThing.name; 
        }); 
      }); 
     }); 

感謝

+1

看一看這些答案http://stackoverflow.com/questions/40375309/cascading-ajax-calls-with- rxjs/40377674#40377674或http://stackoverflow.com/questions/40250882/subscribeing-to-a-nested-observable/40257871#40257871 – martin

回答

0

不要使用subscribe。改爲使用map。 不能測試,但應該看起來更像是這樣的:

this._appService 
    .getUserGames() 
    .map(games => { 
     this._userGames = _.map(games, game => ({ id: game.id, externalGameId: game.externalGameId, name: game.name })); 
     return this._userGames.map(game => { /* this should return an array of observables.. */ 
      return this._externalService 
       .getExternalGameById(game.externalGameId) 
       .map(externalThing => { 
        (<any>game).thumbnail = externalThing.thumbnail; 
        (<any>game).name = externalThing.name; 
        return game; 
       }); 
     }); 
    }) 
    .mergeAll() 
    .subscribe(xx => ...); // here you can subscribe.. 
+0

它沒有。在subscribe()我得到一個observable而不是對象數組。 在閱讀關於reactivex.io/rxjs上的可觀察性的全部理論之後,我發現了兩種解決方案(但事情仍然很模糊)。我會寫一個答案來展示他們 – Etchelon

1

我找到了一種方法,使其工作。我會註釋代碼,以更好地解釋它做什麼,尤其是對自己說:d

this._appService 
     .getUserGames() // Here we have an observable that emits only 1 value: an any[] 
     .mergeMap(games => _.map(games, game => this._externalService.augmentGame(game))) // Here we map the any[] to an Observable<any>[]. The external service takes the object and enriches it with more properties 
     .concatAll() // This will take n observables (the Observable<any>[]) and return an Observable<any> that emits n values 
     .toArray() // But I want a single emission of an any[], so I turn that n emissions to a single emission of an array 
     .subscribe(games => { ... }); // TA-DAAAAA!