我在整个应用程序中都有一个共享服务来处理身份验证,我试图将我的组件逻辑尽可能远离 http 请求,但是,我看到的每一位文档似乎都希望我返回 httpClient Observable,并订阅它并执行所有逻辑来处理组件内部的结果和错误。
我当前的服务代码已完全损坏,但它看起来像这样:
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));
}
}
理想情况下,在组件模块上,我会有类似回调函数的东西,当响应准备好时会调用它。似乎我正在尝试使用 Angular 模式来违背常规,但同时,我不明白为什么 Angular 需要在组件级别执行通用 http 错误的错误处理。
所以我想基本问题是:如何在服务中而不是在单个组件中处理 httpClient 错误?