MST

星途 面试题库

面试题:Angular的HttpClient模块如何实现请求拦截与响应拦截

在一个大型Angular应用中,为了统一处理请求头添加(如添加token)以及响应数据的预处理(如对特定格式的响应数据进行解析),需要使用HttpClient模块的拦截器功能。请详细描述如何创建请求拦截器和响应拦截器,并说明如何将它们注册到Angular应用中。
47.5万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

创建请求拦截器

  1. 导入必要模块 在创建请求拦截器前,需要导入HttpEventHttpHandlerHttpInterceptorHttpRequest等相关模块。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
  1. 创建请求拦截器类 创建一个实现HttpInterceptor接口的类。在intercept方法中,对请求进行处理,比如添加token到请求头。
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 获取token,这里假设从本地存储获取
    const token = localStorage.getItem('token');
    let newRequest = request;
    if (token) {
      newRequest = request.clone({
        setHeaders: {
          Authorization: `Bearer ${token}`
        }
      });
    }
    return next.handle(newRequest);
  }
}

创建响应拦截器

  1. 导入必要模块 同样导入HttpEventHttpHandlerHttpInterceptorHttpResponse等相关模块。HttpResponse用于处理响应数据。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
  1. 创建响应拦截器类 创建一个实现HttpInterceptor接口的类。在intercept方法中,对响应进行处理,比如对特定格式的响应数据进行解析。
@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          // 假设响应数据是特定格式,需要解析
          const newData = this.parseSpecialResponse(event.body);
          return event.clone({ body: newData });
        }
        return event;
      })
    );
  }

  private parseSpecialResponse(data: any): any {
    // 具体的解析逻辑
    if (typeof data === 'string' && data.startsWith('special_')) {
      return JSON.parse(data.substring(8));
    }
    return data;
  }
}

注册拦截器到Angular应用

app.module.ts文件中,将创建好的请求拦截器和响应拦截器注册到providers数组中。

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 { RequestInterceptor } from './request.interceptor';
import { ResponseInterceptor } from './response.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ResponseInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

通过上述步骤,就完成了在Angular应用中创建并注册请求拦截器和响应拦截器的操作。multi: true表示可以有多个拦截器,并且它们会按照注册顺序依次执行。