This isn't the first time I've come across this issue. I need to display data on a web page even if the http request fails, so I have some logic in the err
state. To avoid duplicating code in both subscribe
and err
, I typically write it within the complete
/finally
state.
this.loadingResults = true;
this.service.get().subscribe(data => {
// manipulate the retrieved data
}, err => {
this.initializeData();
}, () => {
this.loadingResults = false;
this.cd.detectChanges();
});
Since I use a spinner on the page to indicate waiting for a response, I want to change the loadingResults
value to false upon receiving the response (whether successful or not) and refresh the page using ChangeDetectorRef
.
The issue arises when the aforementioned code doesn't function correctly, leading me to give up on the 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; // repeating code
this.cd.detectChanges(); // repeating code
});
What is the best approach to utilizing the finally function while preventing redundant code across different response scenarios? It appears that its behavior differs from backend try-catch-finally blocks (such as in Java or C#).