How to correctly retrieve and cache data in Angular service

后端 未结 3 1839
南旧
南旧 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条回答
  •  萌比男神i
    2021-01-29 03:08

    What about your options:

    1) Should work but as for me it requires a lot of code written by hand.

    2) Imagine user won't call getData method but you have already sent redundant request.


    There is a very convenient operator shareReplay that will help you make your cold observable hot.

    import { Observable } from 'rxjs';
    import { shareReplay } from 'rxjs/operators';
    
    
    export class Service {
      private cache$: Observable;
      ...
      getData() {
        if (!this.cache$) {
          this.cache$ = this.anyHttpCall().pipe(
            shareReplay(1)
          );
        }
    
        return this.cache$;
      }
    }
    

    Ng-run Example

提交回复
热议问题