Reputation: 10179
A service sends a http request using HttpClient
core angular service like:
return this.httpService.get<MyObj[]>(myURL).pipe(catchError(errorHandle));
errorHandle: passed as a property to the function calling .get()
I send a 400 Bad Request from my nodejs server which is picked up by the following errorHandle:
handleError(error: HttpErrorResponse) {
this.isLoading = false;
if(error.error instanceof ErrorEvent) {
this.error = error.error.message;
} else {
this.error = "Backend server error, status code:" + error.status
}
return throwError('Something bad happened');
}
Now, this.isLoading
is used in UI to prevent a div from rendering and instead show 'Loading...'. When I set it to false in the handleError
it does update the property, but it doesnt affect the UI. It keeps Loading....
Code for reference:
Component:
handleError(error: HttpErrorResponse) {
this.isLoading = false;
if(error.error instanceof ErrorEvent) {
this.error = error.error.message;
} else {
this.error = "Backend server error, status code:" + error.status
}
return throwError('Something bad happened');
}
ngOnInit() {
//returns 400 Bad Request
this.variablesService.getVariables(URL.MODELVARIABLE+','+URL.METRICVARIABLE, this.handleError).subscribe(variables => {
this.fetchedVariables = variables.map(variable => new Variable(variable));
this.variables = this.fetchedVariables.filter(variable => variable.isglobal);
this.populateGridItems(GRIDNAME.GlobalVariable, this.variables);
this.isLoading = false;
});
}
UI:
<error [error]="error"></error> <!-- content which should show as ive set this.error but still doesnt -->
<div *ngIf="!isLoading && !error">
...content that doesnt show which is fine
</div>
<p *ngIf="isLoading">Loading..</p> <!-- keeps showing even when ive set it to false -->
Upvotes: 1
Views: 1634
Reputation: 29335
you "handle" the error but then you rethrow it and never handle the rethrown error, and an unhandled error breaks an observable stream. You have 2 options:
don't rethrow the error
handleError(error: HttpErrorResponse) {
this.isLoading = false;
if(error.error instanceof ErrorEvent) {
this.error = error.error.message;
} else {
this.error = "Backend server error, status code:" + error.status
}
return empty();
}
or handle the rethrown error in the second argument to subscribe:
this.variablesService.getVariables(URL.MODELVARIABLE+','+URL.METRICVARIABLE, this.handleError).subscribe(variables => {
this.fetchedVariables = variables.map(variable => new Variable(variable));
this.variables = this.fetchedVariables.filter(variable => variable.isglobal);
this.populateGridItems(GRIDNAME.GlobalVariable, this.variables);
this.isLoading = false;
},
(error) => console.log(error, "do whatever you want here"));
Upvotes: 4