使用HttpInterceptor设置标题的问题

时间:2018-12-11 10:14:38

标签: angular typescript

我有以下代码:

// config.service.ts
import { Injectable } from "@angular/core";

@Injectable()
export class ConfigService {
  private language: string = "en";
  constructor() {}
  set Language(lang: string) {
    this.language = lang;
  }
  get Language(): string {
    return this.language;
  }
}

// app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule, APP_INITIALIZER } from "@angular/core";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

import { AnalyticsService, CoreModule, CrossDomainService } from "./core";
import { TileModule } from "./tile/tile.module";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, TileModule, CoreModule.forRoot()],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: onModuleInit,
      multi: true,
      deps: [CrossDomainService, AnalyticsService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

export function onModuleInit(
  crossDomainService: CrossDomainService,
  analyticsService: AnalyticsService
) {
  return () => {
    console.log("App Init");
    crossDomainService.init();
    analyticsService.init();
    return new Promise(resolve => resolve(true));
  };
}

//core.module.ts
import { NgModule, ModuleWithProviders } from "@angular/core";
import { CommonModule } from "@angular/common";
import {
  HTTP_INTERCEPTORS,
  HttpClientModule,
  HttpClient
} from "@angular/common/http";

import { HttpRequestInterceptor } from "./http-request.interceptor";
import { ArticleService } from "./article.service";
import { CrossDomainService } from "./cross-domain.service";
import { AnalyticsService } from "./analytics.service";

import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
import { ConfigService } from "../config.service";

export function translateHttpLoaderFactory(http: HttpClient) {
  //return new TranslateHttpLoader(http);
  return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}

@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: translateHttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [
    ArticleService,
    CrossDomainService,
    AnalyticsService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpRequestInterceptor,
      multi: true
    }
  ]
})
export class CoreModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: CoreModule,
      providers: [ConfigService]
    };
  }
}

//http-request.interceptor.ts
import { Injectable } from "@angular/core";
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest
} from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { ConfigService } from "../config.service";

@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
  language: string = "en";
   constructor(private config: ConfigService) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {    
    const request = req.clone({
      setHeaders: { "Accept-Language": this.config.Language }
    });
    console.log(
      `Request header value : ${request.headers.get("Accept-Language")}`
    );

    return next.handle(request);
  }
}

CrossDomainService,在这种情况下,用于从外部系统获取语言。它是应用程序和外部服务之间的连接器。 enter image description here

此示例中的外部框架将为Sample Angular应用程序提供语言。假设语言的初始值为'en',现在如果将其更新为'es',我会看到HttpRequestInterceptor首先选择了en,然后选择了es。因此,所有API请求都将“ Accept-Language”标头值设为en而不是es。如果外部框架正在发送语言“ fr”,那么在这种情况下,我看到HttpRequestInterceptor首先选择es,然后选择fr。因此,很少有API请求将“ Accept-Language”标头值作为es而不是fr。

有人可以帮助我知道如何解决此问题吗?

2 个答案:

答案 0 :(得分:0)

尝试将setheaders替换为headers

const request = req.clone({headers: req.headers.set('Accept-Language',this.config.Language)});

答案 1 :(得分:0)

我知道这是一个老问题,但如果有人在为拦截器中的所有请求设置“Accept-Language”标头方面遇到困难,请使用:

request = request.clone({
  setHeaders: {
    'Accept-Language': this.config.Language + ';q=0.9,en-US,en;q=0.8'
  }
});

这适用于 Angular 11.2。