简体   繁体   中英

Handling HttpClient Http Errors at the Service Level

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?

您可以在此处处理错误,并且仍然返回可观察对象,就像这样

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM