【问题标题】: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
    })
    

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 2018-06-23
      • 2022-12-18
      • 2020-06-11
      • 1970-01-01
      • 2021-11-22
      • 2019-10-18
      • 2016-05-17
      • 2017-06-11
      相关资源
      最近更新 更多