MST

星途 面试题库

面试题:Angular HTTP客户端拦截器在与后端API交互中的应用

描述Angular HTTP拦截器的作用,如何创建一个HTTP拦截器来统一处理API请求中的错误,比如当后端返回401状态码时,自动跳转到登录页面,并在每次请求头中添加特定的认证令牌。
47.6万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

Angular HTTP拦截器的作用

HTTP拦截器用于在请求发送到服务器之前以及从服务器接收到响应之后,对请求和响应进行拦截和处理。它可以用于添加通用的请求头、处理错误、缓存响应、修改请求或响应的数据等操作,从而实现对HTTP请求和响应的全局控制。

创建HTTP拦截器统一处理API请求错误并添加认证令牌

  1. 创建拦截器类 首先,通过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;
          })
        );
      }
    }
    
  2. 注册拦截器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中注册该拦截器,使其生效。