在Angular中,HttpErrorInterceptor是用来捕获和处理HTTP请求错误的拦截器。然而,它本身无法直接实现重定向功能。但是,我们可以通过以下方法解决这个问题:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
// Redirect to login page
this.router.navigate(['/login']);
}
return throwError(error);
})
);
}
}
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Location } from '@angular/common';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private location: Location) {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
// Redirect to login page
this.location.go('/login');
}
return throwError(error);
})
);
}
}
请注意,以上示例中的重定向路径('/login')仅作为示例,你需要根据你的实际情况进行修改。同时,确保在app.module.ts中将HttpErrorInterceptor添加到providers数组中以进行拦截器的注册。
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './http-error.interceptor';
@NgModule({
imports: [
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
}
]
})
export class AppModule { }
这样,当HTTP请求返回401错误时,用户将被重定向到指定的路由。