2017-01-09 49 views
0

我是RxJS的首發者,只熟悉基礎知識。 現在的情況是: 我有一個observable應該按需加載一些數據。另一個函數應該創建這個需求,並要求第一個觀察者加載下一個數據。RxJS影響從外部觀察

像這樣:

dataPiece$:Observable<DataPiece> = http.load(this.url + this.pieceUrl) 

loadNextPiece(pieceUrl) 
{ 
    this.pieceUrl = pieceUrl; 
    //make the observable to automatically load new piece of data 
    //once pieceUrl is updated 
} 

回答

1

您可以創建一個包含使用Subject的pieceUrls流。對於每件作品都會提出請求並使用switchMap,您可以將所有回覆合併到一個新的流中。

let urlPiece = new Subject(); 
let dataPiece$:Observable<DataPiece>; 

loadNextPiece(pieceUrl) 
{ 
    urlPiece.next(pieceUrl); 
} 

dataPiece$ = urlPiece.asObservable() 
      .switchMap(urlPiece => http.load(this.url + pieceUrl)) 
       .map((response) => { 
        // parse response or just return it 
        return response; 
       }) 
       .catch(error => { 
        // handle error 
       }); 


let subscription = dataPiece$.subscribe((response) => { 
    //do something with response 
}) 
+0

謝謝:)我剛剛以同樣的方式解決了它。 –