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

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

    Just call share() after map and before any subscribe.

    In my case, I have a generic service (RestClientService.ts) who is making the rest call, extracting data, check for errors and returning observable to a concrete implementation service (f.ex.: ContractClientService.ts), finally this concrete implementation returns observable to de ContractComponent.ts, and this one subscribe to update the view.

    RestClientService.ts:

    export abstract class RestClientService {
    
          public GetAll = (path: string, property: string): Observable => {
            let fullPath = this.actionUrl + path;
            let observable = this._http.get(fullPath).map(res => this.extractData(res, property));
            observable = observable.share();  //allows multiple subscribers without making again the http request
            observable.subscribe(
              (res) => {},
              error => this.handleError2(error, "GetAll", fullPath),
              () => {}
            );
            return observable;
          }
    
      private extractData(res: Response, property: string) {
        ...
      }
      private handleError2(error: any, method: string, path: string) {
        ...
      }
    
    }
    

    ContractService.ts:

    export class ContractService extends RestClientService {
      private GET_ALL_ITEMS_REST_URI_PATH = "search";
      private GET_ALL_ITEMS_PROPERTY_PATH = "contract";
      public getAllItems(): Observable {
        return this.GetAll(this.GET_ALL_ITEMS_REST_URI_PATH, this.GET_ALL_ITEMS_PROPERTY_PATH);
      }
    
    }
    

    ContractComponent.ts:

    export class ContractComponent implements OnInit {
    
      getAllItems() {
        this.rcService.getAllItems().subscribe((data) => {
          this.items = data;
       });
      }
    
    }
    

提交回复
热议问题