【问题标题】:RxJS influence observable from outside从外部可观察到的 RxJS 影响
【发布时间】:2017-01-09 19:10:16
【问题描述】:
我是 RxJS 的初学者,只熟悉基础知识。
情况是:
我有一个 observable 应该按需异步加载一些数据。另一个函数应该创建该需求并要求第一个 observable 加载下一条数据。
像这样:
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
}
【问题讨论】:
标签:
javascript
http
asynchronous
rxjs
observable
【解决方案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
})