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

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

    You can build simple class Cacheable<> that helps managing data retrieved from http server with multiple subscribers:

    declare type GetDataHandler = () => Observable;
    
    export class Cacheable {
    
        protected data: T;
        protected subjectData: Subject;
        protected observableData: Observable;
        public getHandler: GetDataHandler;
    
        constructor() {
          this.subjectData = new ReplaySubject(1);
          this.observableData = this.subjectData.asObservable();
        }
    
        public getData(): Observable {
          if (!this.getHandler) {
            throw new Error("getHandler is not defined");
          }
          if (!this.data) {
            this.getHandler().map((r: T) => {
              this.data = r;
              return r;
            }).subscribe(
              result => this.subjectData.next(result),
              err => this.subjectData.error(err)
            );
          }
          return this.observableData;
        }
    
        public resetCache(): void {
          this.data = null;
        }
    
        public refresh(): void {
          this.resetCache();
          this.getData();
        }
    
    }
    

    Usage

    Declare Cacheable<> object (presumably as part of the service):

    list: Cacheable = new Cacheable();
    

    and handler:

    this.list.getHandler = () => {
    // get data from server
    return this.http.get(url)
    .map((r: Response) => r.json() as string[]);
    }
    

    Call from a component:

    //gets data from server
    List.getData().subscribe(…)
    

    You can have several components subscribed to it.

    More details and code example are here: http://devinstance.net/articles/20171021/rxjs-cacheable

提交回复
热议问题