Angular 10不再通过拦截器向请求添加头信息。
创始人
2024-10-15 07:31:42
0

在Angular 10中,拦截器的行为发生了变化,不能直接向请求添加头信息。相反,可以使用HttpHeaders类来创建新的头信息,并将其添加到请求中。

以下是一个示例,展示了如何在拦截器中使用HttpHeaders来向请求添加头信息:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpHeaders } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler) {
    const authToken = 'your-auth-token';

    // 创建新的头信息
    const headers = new HttpHeaders({
      'Authorization': authToken
    });

    // 克隆原始请求,并添加头信息
    const authReq = req.clone({ headers });

    // 将新的请求传递给下一个处理器
    return next.handle(authReq);
  }
}

上述示例中,我们创建了一个名为AuthInterceptor的拦截器,它会在每个请求中添加一个名为Authorization的头信息,并将其值设置为your-auth-token

要在应用中使用该拦截器,需要在AppModule或其他适当的模块中提供它:

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 { AuthInterceptor } from './auth.interceptor';

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

在上述示例中,我们通过将AuthInterceptor提供给HTTP_INTERCEPTORS令牌来注册拦截器。

这样,在应用中的每个请求中,都会通过AuthInterceptor拦截器添加Authorization头信息。

相关内容

热门资讯

每日必看推荐!werplan脚... 每日必看推荐!werplan脚本,hhpoker真能买到挂吗,科技教程(有挂透明)是一款可以让一直输...
热门推荐!wepokerplu... 热门推荐!wepokerplus万能挂,哈糖大菠萝挂,可靠技巧(有挂透视);1.wepokerplu...
揭秘关于!wepoker辅助脚... 此外,数据分析德州(hh poker辅助有用吗)辅助神器app还具备辅助透视行为开挂功能,通过对客户...
揭秘攻略!aapoker透视脚... 1、揭秘攻略!aapoker透视脚本下载,购买wepoker模拟器,存在挂教程(有挂透明)2、进入游...
必看攻略!wejoker辅助软... 必看攻略!wejoker辅助软件,wepoker能不能透视,2025版教程(有挂神器);原来确实真的...
玩家交流!xpoker辅助助手... 玩家交流!xpoker辅助助手,wepoker私人局俱乐部,技巧教程(有挂教程);《WPK辅助透视》...
重大通报!xpoker怎么作弊... 1、重大通报!xpoker怎么作弊,wepoker好友局透视,2025新版教程(有挂方法)。2、we...
科普攻略!wepoker透视最... 1、科普攻略!wepoker透视最简单三个步骤,德普之星私人局透视,玩家教程(有挂方法);详细教程。...
技巧知识分享!wepoker新... 技巧知识分享!wepoker新号好一点吗,wepokerplus辅助,科技教程(有挂辅助)科技教程也...
总算了解!aapoker透视怎... 总算了解!aapoker透视怎么用,约局吧能不能开挂,细节方法(有挂神器)是一款可以让一直输的玩家,...