Angular 10不再通过拦截器向请求添加头信息。
创始人
2024-10-15 07:32:34
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头信息。

相关内容

热门资讯

Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...
Aksnginxdomainb... 在AKS集群中,可以使用Nginx代理服务器实现根据域名进行路由。以下是具体步骤:部署Nginx i...
AddSingleton在.N... 在C#中创建Singleton对象通常是通过私有构造函数和静态属性来实现,例如:public cla...
Alertmanager中的基... Alertmanager中可以使用repeat_interval选项指定在一个告警重复发送前必须等待...