在Angular中,可以使用拦截器来捕获和处理错误响应。以下是一个示例,演示如何处理多个401响应的错误拦截器:
error.interceptor.ts文件,并添加以下代码:import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          // 处理多个401响应
          // 执行相关操作,例如跳转到登录页面或显示错误消息
        }
        return throwError(error);
      })
    );
  }
}
  
app.module.ts文件中,将ErrorInterceptor添加到提供商列表中,以便在应用程序中使用:import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ErrorInterceptor } from './error.interceptor';
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
通过上述步骤,你可以创建一个错误拦截器,并在拦截器中处理多个401响应。当服务器返回401错误时,拦截器会执行相应的操作,例如跳转到登录页面或显示错误消息。