Reputation: 1699
I have a shared service throughout my app that handles authentication, I'm trying to abstract my component logic as far from the http requests as possible, however, every bit of documentation I've seen appears to want me to return the httpClient Observable, and subscribe to it and perform all logic for handling the results and errors inside the component.
My current service code is completely broken, but it looks like this:
userLogin(email: String, password: String) {
const body = { email: email, password: password };
return this.httpClient.post('http://localhost/users/login', body).subscribe(
this.handleResults,
this.handleErrors
);
}
handleResults(results: any) {
if (results.errors) {
console.log(results.errors);
} else {
return results;
}
}
handleErrors(err: HttpErrorResponse) {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.log('A ', err.status, ' error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log('Could not connect to server.');
console.log('Backend returned code ' + err.status + ', body was: ' + JSON.stringify(err.error));
}
}
And ideally on the component module I'd have something like a callback function that is called when the response is ready. It seems like I'm trying to go against the grain with Angular patterns, but at the same time, I can't understand why Angular would require error handling for generic http errors do be performed at the Component level.
So I suppose the basic question is: how do I handle httpClient errors within the service, rather than in the individual components?
Upvotes: 2
Views: 714
Reputation: 18281
You can handle the errors in here, and still return the observable, like so
return this.httpClient.post('http://localhost/users/login', body).catch(this.handleErrors)
Upvotes: 2