1.首先安装ngx-translate依赖
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
2.在app.module.ts中引入
import { TranslateModule, TranslateLoader } from ‘@ngx-translate/core’;
import { TranslateHttpLoader } from ‘@ngx-translate/http-loader’;
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, '../assets/lang/', '.json');
}
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient]
}
})
3.在需要语言国际化的组件中引入translateService;
import { TranslateService } from '@ngx-translate/core';
constructor(
private translate: TranslateService
) {
this.translate.use('en')
}
4.在assets目录下新建lang文件夹存放自己需要国家的json;
5.在组件模板中.app.component.html中使用
angular angular 添加拦截器后无法加载国际化json文件
export function translateHttpLoaderFactory(httpBackend: HttpBackend): TranslateHttpLoader {
return new TranslateHttpLoader(new HttpClient(httpBackend));
}
...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
deps: [HttpBackend],
useFactory: translateHttpLoaderFactory
}
}),