How to correctly retrieve and cache data in Angular service

后端 未结 3 1808
南旧
南旧 2021-01-29 02:29

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

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-29 02:50

    What about initializing a stream in the constructor that is made hot by an initial call to getData? Then the first result is cached in the ReplaySubject

    class Service {
    
      private init = new Subject();
    
      private data = new ReplaySubject(1);
    
      constructor() {
        this.init.pipe(
          take(1),
          switchMap(() => anyHttpCall())
        )
        .subscribe(res => this.data.next(res));   
      }
    
      getData() {
        this.init.next();
    
        return this.data.asObservable();   
      } 
    }
    

提交回复
热议问题