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

前端 未结 21 1328
广开言路
广开言路 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:20

    The implementation you choose is going to depend on if you want unsubscribe() to cancel your HTTP request or not.

    In any case, TypeScript decorators are a nice way of standardizing behavior. This is the one I wrote:

      @CacheObservableArgsKey
      getMyThing(id: string): Observable {
        return this.http.get('things/'+id);
      }
    

    Decorator definition:

    /**
     * Decorator that replays and connects to the Observable returned from the function.
     * Caches the result using all arguments to form a key.
     * @param target
     * @param name
     * @param descriptor
     * @returns {PropertyDescriptor}
     */
    export function CacheObservableArgsKey(target: Object, name: string, descriptor: PropertyDescriptor) {
      const originalFunc = descriptor.value;
      const cacheMap = new Map();
      descriptor.value = function(this: any, ...args: any[]): any {
        const key = args.join('::');
    
        let returnValue = cacheMap.get(key);
        if (returnValue !== undefined) {
          console.log(`${name} cache-hit ${key}`, returnValue);
          return returnValue;
        }
    
        returnValue = originalFunc.apply(this, args);
        console.log(`${name} cache-miss ${key} new`, returnValue);
        if (returnValue instanceof Observable) {
          returnValue = returnValue.publishReplay(1);
          returnValue.connect();
        }
        else {
          console.warn('CacheHttpArgsKey: value not an Observable cannot publishReplay and connect', returnValue);
        }
        cacheMap.set(key, returnValue);
        return returnValue;
      };
    
      return descriptor;
    }
    

提交回复
热议问题