What is the correct way to share the result of an Angular Http network call in RxJs 5?

前端 未结 21 1905
广开言路
广开言路 2020-11-21 06:11

By using Http, we call a method that does a network call and returns an http observable:

getCustomer() {
    return          


        
21条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 06:33

    It's .publishReplay(1).refCount(); or .publishLast().refCount(); since Angular Http observables complete after request.

    This simple class caches the result so you can subscribe to .value many times and makes only 1 request. You can also use .reload() to make new request and publish data.

    You can use it like:

    let res = new RestResource(() => this.http.get('inline.bundleo.js'));
    
    res.status.subscribe((loading)=>{
        console.log('STATUS=',loading);
    });
    
    res.value.subscribe((value) => {
      console.log('VALUE=', value);
    });
    

    and the source:

    export class RestResource {
    
      static readonly LOADING: string = 'RestResource_Loading';
      static readonly ERROR: string = 'RestResource_Error';
      static readonly IDLE: string = 'RestResource_Idle';
    
      public value: Observable;
      public status: Observable;
      private loadStatus: Observer;
    
      private reloader: Observable;
      private reloadTrigger: Observer;
    
      constructor(requestObservableFn: () => Observable) {
        this.status = Observable.create((o) => {
          this.loadStatus = o;
        });
    
        this.reloader = Observable.create((o: Observer) => {
          this.reloadTrigger = o;
        });
    
        this.value = this.reloader.startWith(null).switchMap(() => {
          if (this.loadStatus) {
            this.loadStatus.next(RestResource.LOADING);
          }
          return requestObservableFn()
            .map((res) => {
              if (this.loadStatus) {
                this.loadStatus.next(RestResource.IDLE);
              }
              return res;
            }).catch((err)=>{
              if (this.loadStatus) {
                this.loadStatus.next(RestResource.ERROR);
              }
              return Observable.of(null);
            });
        }).publishReplay(1).refCount();
      }
    
      reload() {
        this.reloadTrigger.next(null);
      }
    
    }
    

提交回复
热议问题