面试题答案
一键面试创建请求拦截器
- 导入必要模块
在创建请求拦截器前,需要导入
HttpEvent
、HttpHandler
、HttpInterceptor
、HttpRequest
等相关模块。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
- 创建请求拦截器类
创建一个实现
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);
}
}
创建响应拦截器
- 导入必要模块
同样导入
HttpEvent
、HttpHandler
、HttpInterceptor
、HttpResponse
等相关模块。HttpResponse
用于处理响应数据。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
- 创建响应拦截器类
创建一个实现
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
表示可以有多个拦截器,并且它们会按照注册顺序依次执行。