angular - http拦截器的错误处理在Angular中不起作用
问题描述
我正在研究 Angular 8
我正在尝试通过拦截器集中错误处理
我的拦截器代码正在运行,但它没有返回任何错误
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { RestService } from './restservice';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private rest : RestService , private route : Router){}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// console.log('jcsjdsjd');
// console.error('xjxfjb');
// console.log(request);
// console.log(next);
return next.handle(request).pipe(catchError(err => {
console.log(err);
if (err.status === 401) {
// auto logout if 401 response returned from api
// this.authenticationService.logout();
location.reload(true);
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
我还在 app.module.ts 的 Providers 中定义了拦截器
providers: [RestService , AuthGuard , commonRest , {
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
}],
我收到的错误 403 请求的响应是:
{
"messagecode": 403,
"message": "not valid token!"
}
解决方案
为了在全局范围内使用拦截器,并且提供程序位于核心模块中,应在拦截器顶部添加 @Injectable({ providedIn: 'root' }) ,如此处https://stackblitz.com/edit/angular-http-interceptor-working-for -lazy-loaded-module?file=src/app/core/token-interceptor.service.ts
推荐阅读
- julia - Julia @btime 找不到内部函数
- c# - 每次保存到数据库时如何擦除表中的数据
- python-3.x - 比较 pandas.DataFrame 中列之间的分类变量
- ios - 带有披露指示器的 SwiftUI 列表按钮
- python - 从没有对象的类中调用函数
- python - 根据其他列值删除重复项(Python)
- sql - 从同一个表更新相同的数据
- c# - I can't run my Nunit test in asp.net core
- php - 如何进行mysql查询并将其转换为php中的数组
- swift - CLGeocoder().geocodeAddressString error codes