我得到了这个拦截器类
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError((err: HttpErrorResponse) => {
if ([401, 403].includes(err.status) && this.authenticationService.usagerValue) {
// auto logout if 401 or 403 response returned from api
this.authenticationService.logout();
console.error("LogOut - 403");
}
let errorMsg = {};
if (err.error instanceof ErrorEvent) {
console.log('this is client side error');
errorMsg = {
Error: `${err.error.message}`,
Type: `Client`
}
}
else {
console.log('this is server side error');
errorMsg = {
Error: `${err.error.message}`,
Type: `Server`,
Code: `${err.status}`,
MsgOrig: `${err.message}`
}
}
console.log(errorMsg);
return throwError(errorMsg);
}))
}
}
然后在我的登录组件中:
this.authService.login(this.form.get('username').value, this.form.get('password').value)
.pipe(first())
.subscribe(
next => {
this.router.navigate([this.returnUrl]);
},
error => {
if(error === undefined)
this.alertService.error("Erreur not defined!", { id: 'alertLogin' })
else
this.alertService.error(error.message, { id: 'alertLogin' })
this.loading = false;
});
但是 loginComponent 中的错误变量始终是未定义的。为什么?如果我返回 err 属性(在我的拦截器中),在我的登录中我只能检索我的 Web 服务器发送的消息的 error.message 部分。谢谢