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

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

    rxjs version 5.4.0 (2017-05-09) adds support for shareReplay.

    Why use shareReplay?

    You generally want to use shareReplay when you have side-effects or taxing computations that you do not wish to be executed amongst multiple subscribers. It may also be valuable in situations where you know you will have late subscribers to a stream that need access to previously emitted values. This ability to replay values on subscription is what differentiates share and shareReplay.

    You could easily modify an angular service to use this and return an observable with a cached result that will only ever make the http call a single time (assuming the 1st call was successfull).

    Example Angular Service

    Here is a very simple customer service that uses shareReplay.

    customer.service.ts

    import { shareReplay } from 'rxjs/operators';
    import { Observable } from 'rxjs';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    export class CustomerService {
    
        private readonly _getCustomers: Observable;
    
        constructor(private readonly http: HttpClient) {
            this._getCustomers = this.http.get('/api/customers/').pipe(shareReplay());
        }
    
        getCustomers() : Observable {
            return this._getCustomers;
        }
    }
    
    export interface ICustomer {
      /* ICustomer interface fields defined here */
    }
    

    Note that the assignment in the constructor could be moved to the method getCustomers but as observables returned from HttpClient are "cold" doing this in the constructor is acceptable as the http call will only every be made with the first call to subscribe.

    Also the assumption here is that the initial returned data does not get stale in the lifetime of the application instance.

提交回复
热议问题