【问题标题】:Handling HttpClient Http Errors at the Service Level在服务级别处理 HttpClient Http 错误
【发布时间】: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 错误?

【问题讨论】:

标签: javascript angular subject angular4-httpclient


【解决方案1】:

你可以在这里处理错误,并且仍然返回 observable,就像这样

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2014-12-20
    相关资源
    最近更新 更多