我正在尝试解决另一个Angular问题-您能帮我吗?在我的组件中,我有一个登录功能-像这样:
onLogin() {
if (this.loginForm.valid) {
const email = this.loginForm.get(['email']).value;
const password = this.loginForm.get(['password']).value;
this.ls.login(email, password).subscribe(
result => {
this.saveToken(result);
},
error => {
this.errorMessage = error;
this.loginForm.reset();
}
);
} else {
this.updateErrorMessage();
}
}
我的服务功能如下所示:
login(email: string, password: string): Observable<string> {
const apiUrl = environment.apiHostLumen + '/admin/login?email=' + email + '&password=' + password;
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
return this.http.get(apiUrl, options).pipe(
retry(3),
map(res => res.json()),
map(data => {
return data.token;
}),
catchError(this.ehs.handleError('login'))
);
}
现在,我已经按照Angular文档中所述完全实现了用于错误处理的功能。我已经将该功能外包了,它看起来像这样:
handleError<T> (operation = 'operation', result?: T) {
return (error: HttpErrorResponse): Observable<T> => {
const userMessage = error.message;
return throwError(userMessage);
};
}
但是如何访问API响应的主体?
error.message
始终未定义。我只能访问status
代码和url
。如果API返回不同于200
的错误代码,如何访问响应正文?非常感谢
最佳答案
您可以为此使用HttpInterceptor
。由此,您可以在一个类中处理所有http错误。您可以在正式的官方文档中阅读有关Intercepting requests and responses的更多信息。
通过使用intercept
方法,您可以拦截每个请求和响应。
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(req)
.pipe(catchError(err => {
if (err instanceof HttpErrorResponse) {
this.onError(err);
}
return throwError(err);
}));
}
private onError(response: HttpErrorResponse): void {
const status: number = response.status;
const serverErrorMessage = response.error;
switch(status) {
case 400:
console.log("Bad request"); //or you can print the serverErrorMessage
case 404:
console.log("Not found");
}
}
关于angular - Angular handleError : How to get custom API error messages?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50944140/