面试题答案
一键面试HTTP请求拦截器工作原理
在Angular中,HTTP请求拦截器是一种强大的机制,它允许开发者在HTTP请求发送之前和响应接收之后对请求或响应进行拦截和处理。
当应用发起一个HTTP请求时,Angular会检查是否配置了HTTP拦截器。如果有,请求会依次经过每个拦截器。拦截器可以对请求进行修改,例如添加请求头(如身份验证令牌)、转换请求体数据等。之后,修改后的请求会被发送到服务器。
当服务器返回响应时,响应也会反向经过这些拦截器。拦截器可以处理响应,比如检查响应状态码、处理错误、转换响应数据等。
常见应用场景
- 身份验证(添加Authorization头):在每个请求中添加JWT(JSON Web Token)等身份验证令牌。假设使用JWT进行身份验证,拦截器代码示例如下:
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = localStorage.getItem('token');
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
return next.handle(request);
}
}
- 错误处理:统一处理HTTP响应中的错误。例如,当服务器返回401(未授权)状态码时,自动重定向到登录页面。
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, catchError } from 'rxjs';
import { Router } from '@angular/router';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
this.router.navigate(['/login']);
}
throw error;
})
);
}
}