Is not first time when I encounter this problem. Because I want to display some data on web page, even if the http request failed, I have some logique inside the err state. To not duplicate code in subscribe and err, I use to write it inside complete/finally state.
this.loadingResults = true;
this.service.get().subscribe(data => {
// do something with the data
}, err => {
this.initializeData();
}, () => {
this.loadingResults = false;
this.cd.detectChanges();
});
Because in the page I use a spinner how time I wait for the response, when it came (successfully or not, on subscribe or err), I want to change the loadingResults value to false and using ChangeDetectorRef to refresh the data on page.
The problem is that the above code will not work correctly and I need to renounce at finally function:
this.loadingResults = true;
this.service.get().subscribe(data => {
// do something with the data
this.loadingResults = false;
this.cd.detectChanges();
}, err => {
this.initializeData();
this.loadingResults = false; // duplicate
this.cd.detectChanges(); // duplicate
});
What's the best way to use finally and avoid repeat code in the rest of response types? I see its behavior is not like try-catch-finally from backend (Java/C#)