By using Http, we call a method that does a network call and returns an http observable:
getCustomer() {
return
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,
onnext
.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.