RxJS Ab(使用)Observables的map函数

时间:2017-02-04 18:58:58

标签: angular dictionary rxjs observable interceptor

在我的Angular2设置中,我有一个调用服务方法的组件。 service方法返回一个Observable,组件订阅它。

由于我希望服务缓存最近的调用,我会使用map函数拦截Observable中的数据。示例性服务方法如下所示

provideData():Observable<Data> {
  return this.http.get(url).
    map(resp => resp.json()).
    map(data => { 
          this.cachedData = _.cloneDeep(data);
          return data;
    }
}

这种方法对我有用,但是,我不确定我是否滥用了没有映射任何内容的map函数。它只是一个拦截数据的拦截器。是否有更好或更推荐的方式?

PS:这不一定是关于缓存,而是适用于非映射操作的map函数。 In this questionGünter广泛认可的答案实际上是相同的,并使用map。另一方面,用户olsn在评论中指出do更合适。

1 个答案:

答案 0 :(得分:1)

PublishReplay使您的流多播兼容并缓存源流。

provideData():Observable<Data> {
  return this.http.get(url)
    .map(resp => resp.json())
    .publishReplay();
}

有关此运算符如何工作的详细说明,请查看Making a lazy, cached observable that only execute the source once