现代Angular i18n:如何设置MissingTranslationStrategy?
解决Angular i18n未找到翻译警告的配置方法
要禁用Angular原生i18n运行时的未翻译警告,你可以通过配置MissingTranslationStrategy来实现,根据项目架构(NgModule或独立组件),配置方式略有不同:
1. NgModule架构(使用bootstrapModule)
有两种配置途径:
- 在AppModule的providers中注入令牌:
导入MissingTranslationStrategy和TRANSLATION_MISSING_STRATEGY,在providers数组中指定忽略策略:import { MissingTranslationStrategy, TRANSLATION_MISSING_STRATEGY } from '@angular/localize'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [BrowserModule], declarations: [AppComponent], providers: [ { provide: TRANSLATION_MISSING_STRATEGY, useValue: MissingTranslationStrategy.Ignore } ], bootstrap: [AppComponent] }) export class AppModule {} - 在
bootstrapModule调用时传入选项:
直接在启动模块时指定missingTranslation参数:import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { MissingTranslationStrategy } from '@angular/localize'; platformBrowserDynamic().bootstrapModule(AppModule, { missingTranslation: MissingTranslationStrategy.Ignore }) .catch(err => console.error(err));
2. 独立组件架构(使用bootstrapApplication)
独立组件模式下,需要在bootstrapApplication的providers数组中注入TRANSLATION_MISSING_STRATEGY令牌:
import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { MissingTranslationStrategy, TRANSLATION_MISSING_STRATEGY } from '@angular/localize'; bootstrapApplication(AppComponent, { providers: [ { provide: TRANSLATION_MISSING_STRATEGY, useValue: MissingTranslationStrategy.Ignore } ] });
可选策略值说明
MissingTranslationStrategy.Ignore:完全忽略未翻译项,不输出任何警告MissingTranslationStrategy.Warning:默认值,输出警告信息MissingTranslationStrategy.Error:抛出错误终止应用
内容的提问来源于stack exchange,提问作者O'Rooney
相关产品推荐
相关产品推荐

