2016-06-20 124 views
0

我在Angular2應用程序中編寫的服務(稱爲ContentService)中有一個Observable,看起來像這樣(我編輯了這個/減少了內容以便於閱讀):使用RxJS在Angular2中組合兩個可觀察的流.flatmap

@Injectable() 
export class ContentService { 

    constructor(private http:Http, private apiService:ApiService) { 

     this.content = this.http.get('src/i18n/en.json') 
      .map((res:Response) => { 
       let json: {} = res.json(); 
       return mapData(json); 
      }) 

     mapData() { 
      // function stuff to format data 
     } 

現在,我想打個電話給我注入apiService,它返回具有相同的結構,什麼是this.content產生一個JSON對象。請注意,this.content來自本地json文件,而apiStream來自第三方API/http提要。我需要將apiService的結果concaching(或添加)到this.content observable。我認爲flapMap是解決這個問題的最好方法,但我犯了一些語法錯誤(如果我正在以正確的方式進行討論)。我正在考慮添加像這樣的新內容

this.content = this.http.get('src/i18n/' + this.userLang + '.json') 
      .map((res:Response) => { 
       let json: {} = res.json(); 
       return mapData(json); 
      }) 
      .flatMap(() => { 
       apiService.getAllCurrentListings().subscribe(response => { 
        return mapData(response); 
       }) 
      }); 

但是,這是產生一個錯誤,所以我顯然做錯了什麼。我是否應該打電話給我的API服務,就像不在.flapMap中一樣,我得到我想要的數據,所以我明顯犯了一個語法錯誤。如何將apiService數據添加到我原來的this.content調用結果中?

非常感謝提前。

回答

0

this.content應該保存什麼數據?

在你的代碼中,它是從this.http.get獲取並觀察的。如果你想獲得http數據響應,你應該這樣做。

Injectable() 
 
export class ContentService { 
 

 
    constructor(private http:Http, private apiService:ApiService)  { 
 

 
     his.http.get('src/i18n/en.json') 
 
      .map((res:Response) => { 
 
       let json: {} = res.json(); 
 
       return mapData(json); 
 
      }) 
 
      .subscribe(mappedData => 
 
         this.content = mappedData) 
 

 
     mapData() { 
 
      // function stuff to format data 
 
     } 
 
    } 

雖這麼說,你能想象你的第二個片斷也是錯誤的。 但是我不會在這種情況下使用flatMap運算符,因爲我知道apiService.getAllCurrentListings對第一個http調用沒有數據依賴性。因此,forkJoin運算符可以做到這一點。

import {Observable} from 'rxjs/Observable' 
 

 
Observable.forkJoin([ 
 
    this.http.get('src/i18n/' + this.userLang + '.json'), 
 
    this.apiService.getAllCurrentListings()]) 
 
    .map(res => { 
 
    this.content = this.mapData(res[0].json()) 
 
    /* again, I dind't get what this.content is supposed to hold, but we need a different variable to store the second result */ 
 
    this.content2 = this.mapData(res[1].json()) 
 
    }) 
 

.forkJoin基團N觀測量中的陣列結構,從而每個響應必須相應地使用陣列索引讀取。

如果這不是你所需要的,請提供this.content定義以及它應該存儲的內容。

+0

感謝您的更新,其實我決定去與forkJoin但是我需要重新開發以此爲'this.content'不應該等待api服務 –

1

這是我想出了一個解決方案:

this.content = Observable.forkJoin(
      this.http.get('src/i18n/en.json').map((res:Response) => res.json()), 
      apiService.getAllCurrentListings() 
     ).map(res => { 
      let tempJson:{} = Object.assign(res[0], res[1]); 
      return mapData(tempJson); 
     }) 
+0

謝謝,這也適用於我,它不像flatMap那樣混亂 – nisenish