Http拦截器解决方案:
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(private router: Router) {
}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
{
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
const _ = this.router.navigate(['login']);
}
return throwError(error);
})
);
}
}
然后将其定义为模块中的提供者
@NgModule({
declarations: [],
imports: [],
exports: [],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UnauthorizedInterceptor,
multi: true,
}
]
})