You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17中如何为翻译模块的请求添加HttpContext

为Angular 17翻译模块的请求添加HttpContext以跳过拦截器处理

由于默认的TranslateHttpLoader没有提供直接配置请求选项的入口,你需要自定义一个加载器,在翻译请求中附加IS_PUBLIC_API上下文,让拦截器跳过处理这些请求。

步骤1:创建自定义TranslateHttpLoader

继承原TranslateHttpLoader,重写getTranslation方法,在HTTP请求中添加指定上下文:

import { HttpClient, HttpContext } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
// 替换为你的IS_PUBLIC_API常量实际路径
import { IS_PUBLIC_API } from '../interceptors/auth.interceptor';

export class CustomTranslateHttpLoader extends TranslateHttpLoader {
  constructor(http: HttpClient) {
    super(http);
  }

  getTranslation(lang: string): Observable<any> {
    // 沿用原加载器的URL生成逻辑
    const url = `${this.prefix}${lang}${this.suffix}`;
    // 附加IS_PUBLIC_API上下文
    const requestOptions = {
      context: new HttpContext().set(IS_PUBLIC_API, true)
    };
    return this.http.get(url, requestOptions);
  }
}

步骤2:修改TranslateModule配置

将原加载器替换为自定义的CustomTranslateHttpLoader:

TranslateModule.forRoot({
  defaultLanguage: 'fr',
  loader: {
    provide: TranslateLoader,
    useFactory: (http: HttpClient) => new CustomTranslateHttpLoader(http),
    deps: [HttpClient]
  },
})

这样所有翻译模块发出的请求都会自动携带IS_PUBLIC_API上下文,你的拦截器会识别并跳过对这些请求的处理。

内容的提问来源于stack exchange,提问作者naspy971

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:22:16