- 安装依赖
npm install @ngx-translate/core –-save
npm install @ngx-translate/http-loader --save
- 配置国际化
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, './assets/i18n/', '.json?nocache=' + (new Date()).getTime());
}
export class MyMissingTranslationHandler implements MissingTranslationHandler {
handle(params: MissingTranslationHandlerParams) {
return 'XXX';
}
}
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
TranslateModule.forRoot({
missingTranslationHandler: {
provide: MissingTranslationHandler,
useClass: MyMissingTranslationHandler
},
useDefaultLang: false,
defaultLanguage: 'zh-CN',
loader: {
provide: TranslateLoader,
useFactory: (HttpLoaderFactory),
deps: [HttpClient]
}
})
],
- 多语言切换方法调用
export class AppComponent implements OnInit {
lang = true;
constructor(private translate: TranslateService) {
this.translate.use('zh-CN');
console.log(this.translate.getBrowserLang());
}
ngOnInit(): void {
this.translate.onLangChange.subscribe((params) => {
console.log(params);
})
}
changeLang(): void {
if (this.lang) {
this.translate.use('en-US');
} else {
this.translate.use('zh-CN');
}
this.lang = !this.lang;
}
}