What would be the best way if I have to top a loading. I have the following.
loadProducts() {
this.subscription = this._productService.getAll()
.subscribe(products => {
this.isLoading = false
this.products = products;
},
() => this.isLoading = false,
() => this.isLoading = false
);
}
this.isLoading = false in "next", "error" and "complete" Obviously it is to ensure that loading stops even when there is an error. There's a way to reduce this, let's say, something like attaching a callback or lambda to the subscribe and having it run in all cases
A common practice is to use RxJS operators for this case like finalize
or tap
and catchError
:
loadProducts() {
this.subscription = this._productService.getAll()
.pipe(
finalize(() => (this.isLoading = false)),
catchError(error => {
this.isLoading = false;
return throwError(error);
})
)
.subscribe(products => this.products = products);
}