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
相关产品推荐
相关产品推荐

