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

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

    What we want to do, is ensure that this does not cause multiple network requests.

    My personal favourite is to make use of async methods for calls that make network requests. The methods themselves don't return a value, instead they update a BehaviorSubject within the same service, which components will subscribe to.

    Now Why use a BehaviorSubject instead of an Observable? Because,

    • Upon subscription BehaviorSubject returns the last value whereas A regular observable only triggers when it receives an onnext.
    • If you want to retrieve the last value of the BehaviorSubject in a non-observable code (without a subscription), you can use the getValue() method.

    Example:

    customer.service.ts

    public customers$: BehaviorSubject = new BehaviorSubject([]);
    
    public async getCustomers(): Promise {
        let customers = await this.httpClient.post(this.endPoint, criteria).toPromise();
        if (customers) 
            this.customers$.next(customers);
    }
    

    Then, wherever required, we can just subscribe to customers$.

    public ngOnInit(): void {
        this.customerService.customers$
        .subscribe((customers: Customer[]) => this.customerList = customers);
    }
    

    Or maybe you want to use it directly in a template

  • ...
  • So now, until you make another call to getCustomers, the data is retained in the customers$ BehaviorSubject.

    So what if you want to refresh this data? just make a call to getCustomers()

    public async refresh(): Promise {
        try {
          await this.customerService.getCustomers();
        } 
        catch (e) {
          // request failed, handle exception
          console.error(e);
        }
    }
    

    Using this method, we don't have to explicitly retain the data between subsequent network calls as it's handled by the BehaviorSubject.

    PS: Usually when a component gets destroyed it's a good practice to get rid of the subscriptions, for that you can use the method suggested in this answer.

提交回复
热议问题