Angular通用的HttpInterceptor运行两次
创始人
2024-10-29 19:00:27
0

在Angular中,HttpInterceptor可以用于在发送HTTP请求和接收HTTP响应之前执行一些操作。然而,有时会遇到HttpInterceptor运行两次的问题。以下是解决这个问题的一种方法:

  1. 创建一个名为UniqueInterceptor的HttpInterceptor类。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class UniqueInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest, next: HttpHandler): Observable> {
    // 检查请求头中是否已经存在unique-interceptor标记
    if (request.headers.has('unique-interceptor')) {
      // 如果已存在,则直接通过
      return next.handle(request);
    }

    // 向请求头中添加unique-interceptor标记
    const modifiedRequest = request.clone({
      headers: request.headers.set('unique-interceptor', 'true')
    });

    // 继续处理修改后的请求
    return next.handle(modifiedRequest);
  }
}
  1. 在app.module.ts文件中,将UniqueInterceptor添加到HTTP_INTERCEPTORS提供者。
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 { UniqueInterceptor } from './unique.interceptor';

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

通过以上步骤,我们在每个HTTP请求中添加了一个名为"unique-interceptor"的请求头标记。当第二次拦截时,检查请求头中是否已经存在该标记,如果存在,则直接通过,避免了重复拦截的问题。

这样,HttpInterceptor就只会运行一次了。

相关内容

热门资讯

有挂一下!丽水都莱辅助工具试用... 有挂一下!丽水都莱辅助工具试用,泸州家乡大二辅助,原来真的有挂(哔哩哔哩)所有人都在同一条线上,像星...
科普一下!人海大厅挂什么好,开... 科普一下!人海大厅挂什么好,开心泉州小程序辅助,都是真的有挂(哔哩哔哩)开心泉州小程序辅助辅助器是一...
曝光一下!枫叶辅助器,牛总管怎... 曝光一下!枫叶辅助器,牛总管怎么做辅助,一贯真的有挂(哔哩哔哩)1、枫叶辅助器有没有辅助教程、枫叶辅...
分享一下!卡五星辅助,牛总管辅... 分享一下!卡五星辅助,牛总管辅助神器,一直有挂(哔哩哔哩)在进入牛总管辅助神器软件靠谱后,参与本局比...
分享一下!荆州晃晃麻将圣盛辅助... 分享一下!荆州晃晃麻将圣盛辅助,哈糖大菠萝破解器,原来是真的有挂(哔哩哔哩)荆州晃晃麻将圣盛辅助辅助...
揭幕一下!创思维激k透视挂,吉... 揭幕一下!创思维激k透视挂,吉祥填大坑有插件吗,一贯有挂(哔哩哔哩)1.吉祥填大坑有插件吗 选牌创建...
解密一下!0759湛江吴川三脚... 解密一下!0759湛江吴川三脚鸡辅助,约战丹东辅助,都是是真的有挂(哔哩哔哩)1、进入到0759湛江...
解密一下!微乐山西小程序破解器... 解密一下!微乐山西小程序破解器,手机游戏辅助脚本工具,都是真的有挂(哔哩哔哩)1、许多玩家不知道微乐...
推荐一下!小程序游戏辅助器,多... 推荐一下!小程序游戏辅助器,多乐辅助器免费版,确实真的有挂(哔哩哔哩)1、在小程序游戏辅助器插件功能...
科普一下!来来拼十辅助,多乐跑... 科普一下!来来拼十辅助,多乐跑得私人房间作弊视频,都是有挂(哔哩哔哩)1、用户打开应用后不用登录就可...