Issue
In many projects, I see this kind of subscription code:
isLoading: boolean; // the variable initializes, for instance, the display of the loader
The next step is to load the content of the page:
this.loadSomething(): void {
this.isLoading = true;
this.someService.getMethod(data)
.subscribe(response => {
if (response) {
...do something
}
},
(errors: HttpErrorResponse) => {
...do something
},
() => {
this.isLoading = false;
}
);
};
As far as I know, the third .complete() subscription argument will not be executed in case of an error.
Thus, if we receive an error from the server, this.isLoading = false; will not be executed and we will not see the data page, and we will see an infinite loader.
In my code I always write like this:
this.loadSomething(): void {
this.isLoading = true;
this.someService.getMethod(data)
.subscribe(response => {
this.isLoading = false;
if (response) {
...do something
}
},
(errors: HttpErrorResponse) => {
this.isLoading = false;
...do something
}
);
};
..that is, without using the .complete() block
I can't figure out why it's written this way or am I missing something? How do you subscribe and how do you do it correctly?
Solution
You can use finalize operator to handle loading disablement, it'll run after upon complete or error
this.someService.getMethod(data).
pipe(finalize(()=>this.loading=false))
.subscribe()
Answered By - Fan Cheung
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.