【问题标题】:rxjs http request is not cachedrxjs http 请求没有被缓存
【发布时间】:2018-08-08 00:43:41
【问题描述】:

我正在尝试理解 rxjs publishReplayrefCountshare 我想要实现的是缓存 http 请求,如此处所述What is the correct way to share the result of an Angular Http network call in RxJs 5?

这就是我的想法

export class TestService {

  constructor(private http: HttpClient) {}
  getData(): Observable<any> {
    return this.http.get('https://httpbin.org/anything').map((data: any) => {
    console.log('getting data');

      return Math.floor(Math.random() * 20);
    }).publishReplay(1).refCount();
  } 
}

调用它

t.getData().subscribe((data: any) => console.log(data));
t.getData().subscribe((data: any) => console.log(data));

请求通常会发出两次。

只是为了了解造成这种情况的原因:

如果我第二次订阅时 observable(http 请求)尚未完成,我是否更正了此行为?

如果我将第二个t.getData() 移动到第一个订阅中,那么接下来只有一个请求是模式。

here is a stackblitz with the code

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

    每次调用 getData() 方法时,它都会返回一个新的 observable - 将冷的 observable 转换为热的 observable 并不重要。

    .publishReplay 更合适的用法是保持 Observable 的相同实例。

    例如:

    export class TestService {
      data: Observable<any>;
      constructor(private http: HttpClient) {
         this.data = this.getData();
      }
      getData(): Observable<any> {
        return this.http.get('https://httpbin.org/anything').map((data: any) =>{
        console.log('getting data');
    
          return Math.floor(Math.random() * 20);
        }).publishReplay(1).refCount();
      } 
    }
    

    调用它:

    this.data.subscribe(t=> ...);
    this.data.subscribe(t=> ...);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多