面试题答案
一键面试Angular HTTP拦截器的作用
HTTP拦截器用于在请求发送到服务器之前以及从服务器接收到响应之后,对请求和响应进行拦截和处理。它可以用于添加通用的请求头、处理错误、缓存响应、修改请求或响应的数据等操作,从而实现对HTTP请求和响应的全局控制。
创建HTTP拦截器统一处理API请求错误并添加认证令牌
- 创建拦截器类
首先,通过Angular CLI生成一个拦截器类:
这会生成一个类似ng generate interceptor http - interceptors
http - interceptors.ts
的文件,内容如下:import { Injectable } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable, catchError } from 'rxjs'; import { Router } from '@angular/router'; @Injectable() export class HttpInterceptorsService implements HttpInterceptor { constructor(private router: Router) {} intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { // 添加认证令牌到请求头 const token = localStorage.getItem('token');// 假设从localStorage获取令牌 let newRequest = request; if (token) { newRequest = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); } return next.handle(newRequest).pipe( catchError((error) => { if (error.status === 401) { // 后端返回401状态码,跳转到登录页面 this.router.navigate(['/login']); } throw error; }) ); } }
- 注册拦截器
在
app.module.ts
中注册拦截器:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform - browser'; import { AppComponent } from './app.component'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { HttpInterceptorsService } from './http - interceptors.service'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, HttpClientModule], providers: [ { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorsService, multi: true } ], bootstrap: [AppComponent] }) export class AppModule {}
上述代码首先创建了一个拦截器类HttpInterceptorsService
,在intercept
方法中,它先添加认证令牌到请求头,然后对响应进行错误处理,当遇到401状态码时,导航到登录页面。最后在app.module.ts
中注册该拦截器,使其生效。