简体   繁体   English

外部可观察到的RxJS影响

[英]RxJS influence observable from outside

I'm a starter with RxJS and only familiar with basics. 我是RxJS的入门者,并且只熟悉基础知识。 The situation is: I have an observable that should load some data asynchronously on demand. 情况是:我有一个可观察的对象,可以按需异步加载一些数据。 And the other function should create that demand and ask the first observable to load next piece of data. 而另一个函数应该创建该需求并要求第一个可观察到的加载下一个数据。

Like so: 像这样:

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
}

You can create a stream that contains the pieceUrls using a Subject . 您可以使用Subject创建一个包含pieceUrl的流。 For every piece the request will be made and using switchMap you can merge all responses into a new stream. 每一件都会发出请求,使用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
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM