我希望用户在令牌过期时退出我的应用程序,但它在我设置的条件下遇到了一些问题。
logout.interceptor.ts
export class LogoutInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status == 401 && error.error.error === 'Token expired') {
this.authService.logout();
}
console.log(error.status);
console.log(error.error.error);
return throwError(error);
})
);
}
}
控制台上记录的结果是我想看到的结果,但条件根本不起作用。
我尝试在 home.component.ts 文件中处理这个问题,逻辑工作正常。
home.component.ts
export class HomeComponent implements OnInit {
homeData!: any
constructor(private homeService: HomeService, private toastr: ToastrService, private authService: AuthService) {
}
ngOnInit() {
this.getAll();
}
getAll() {
this.homeService.getAll().subscribe({
next: (res: any) => {
this.homeData = res;
console.log(this.homeData)
},
error: (error) => {
if (error.status === 401 && error.error.error === "Token has expired") {
this.toastr.error(error.error.error, error.statusText)
console.log("Error On Home Component", error);
return this.authService.logout();
}
this.toastr.error(error.error.error, error.statusText)
console.log("Error On Home Component", error);
}
})
}
}
这是app.module.ts
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {HTTP_INTERCEPTORS, HttpClientModule} from "@angular/common/http";
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AuthInterceptor} from "./services/auth.interceptor";
import {ToastrModule} from 'ngx-toastr';
import {LogoutInterceptor} from "./services/logout.interceptor";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
ToastrModule.forRoot()
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: LogoutInterceptor, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
拦截器如果条件不能正常工作
即使令牌已经过期,拦截器也不会将用户从应用程序中注销
您的 Angular 应用程序中似乎有两个 HTTP 拦截器:AuthInterceptor 和 LogoutInterceptor。 AuthInterceptor 可能处理与身份验证相关的任务,而 LogoutInterceptor 应该在满足特定条件时处理注销。
在您的 LogoutInterceptor 中,您正在检查:
if (error.status == 401 && error.error.error === 'Token expired') {
this.authService.logout();
}
但是在您的 HomeComponent 中,您正在检查:
if (error.status === 401 && error.error.error === "Token has expired") {
// ...
}
拦截器中的错误消息是“Token已过期”,而在组件中则是“Token已过期”。这些消息应该匹配拦截器才能正常工作。
要解决此问题,请确保拦截器和组件中的错误消息匹配。您可以更新其中一个以匹配另一个。例如,您可以将拦截器更改为:
if (error.status == 401 && error.error.error === 'Token has expired') {
this.authService.logout();
}
当 HTTP 请求拦截器按预期工作期间遇到具有正确错误消息的 401 状态代码时。