在服务级别处理 HttpClient Http 错误

Handling HttpClient Http Errors at the Service Level

我在整个应用程序中都有一个处理身份验证的共享服务,我试图尽可能远离 http 请求来抽象我的组件逻辑,但是,我看到的每一点文档似乎都希望我这样做return 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 错误?

您可以在此处处理错误,并且仍然 return observable,就像这样

return this.httpClient.post('http://localhost/users/login', body).catch(this.handleErrors)