【发布时间】:2017-10-02 20:25:20
【问题描述】:
我在整个应用程序中都有一个共享服务来处理身份验证,我试图将我的组件逻辑尽可能远离 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 错误?
【问题讨论】:
-
第三种选择是通过拦截器处理 http 错误,这是我最喜欢的方法,因为您可以全局“设置并忘记”样式处理错误。 angular.io/guide/http#intercepting-all-requests-or-responses
标签: javascript angular subject angular4-httpclient