如何在Angular服务中正确检索和缓存数据 [英] How to correctly retrieve and cache data in Angular service

查看:245
本文介绍了如何在Angular服务中正确检索和缓存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在有角度的应用程序中,我有一些服务,需要通过http请求检索某些数据,并通过BehaviorSubject将其共享给消费者.它具有这样的实现:

Frequently, in angular app, i have some service, which need to retreive some data through http request and share it to consumers through BehaviorSubject. It have implementation like this:

class Service { 

  private data = new BehaviorSubject();

  getData() {
    if (!this.data.getValue()) {
      anyHttpCall().subscribe(res => this.data.next(res));
    }

    return this.data.asObservable();
  } 
}

这种方法的主要原理是,当应用程序的某些组件在没有值时同时调用getData()时,它将触发多个http调用并发出数据,因此我发现了两种防止它的方法:

The main priblem of this approach is that when some components of application will call getData() at the same time when there is no value yet, it will trigger multiple http calls and data emits, so i found 2 ways to prevent it:

1)存储表明请求状态的布尔变量

1)Store boolean variable which says about request status

class Service { 

  private data = new BehaviorSubject();   

  private pendingResult = false;

  getData() {
    if (!this.data.value && !this.pendingResult) {
      this.pendingResult = true;
      anyHttpCall().subscribe(res =>   {
        this.data.next(res);
        this.pendingResult = false;
      }
    }

    return this.data.asObservable();
  } 
}

2)在服务构造函数中获取数据

2)Fetch data in service constructor

class Service { 

  private data = new BehaviorSubject();  

  constructor() {
    anyHttpCall().subscribe(resthis.data.next(res));
  }

  getData() {
    return this.data.asObservable();
  } 
}

那么,哪种方法是最好的,为什么?

So which of this or another approaches is the best and why

推荐答案

最好的方法是使用rxjs shareReplay .该运算符返回一个Observable,该Observable共享对基础源的单个订阅.换句话说,使我们的可观察性变得炙手可热.

The best way is using rxjs shareReplay. This operator returns an Observable that shares a single subscription to the underlying source. In other words, turns our observable hot.

const CACHE_SIZE = 1;
class Service { 

  private _data$: Observable<YourType>;

  get data(): Observable<YourType> {
    if (!this._data$) {
      this._data$ = anyHttpCall()
        .pipe(shareReplay({ refCount: true, bufferSize: CACHE_SIZE })
      );
    }
    return this._data$;
  }
}

bufferSize 确定重播缓冲区的最大元素数,即为每个订阅者缓存和重播的元素数.

The bufferSize determines the maximum element count of the replay buffer, that is the number of elements that are cached and replayed for every subscriber.

这篇文章对此做了很好的解释: https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html

This post explains this very good: https://blog.thoughtram.io/angular/2018/03/05/advanced-caching-with-rxjs.html

这篇关于如何在Angular服务中正确检索和缓存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆