1、NzI18nService服务

参考:https://ng.ant.design/docs/i18n/zh

2、ngx-translate插件

1)安装依赖

npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader --save
2)引入TranslateModule模块

*在AppModule中引入TranslateModule模块
import {TranslateModule} from '@ngx-translate/core';

*根路由引入TranslateModule模块相关配置并在imports中配置如下:
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {HttpClient} from '@angular/common/http';

*配置AppModule的 imports如下:
TranslateModule.forRoot({
       loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
             deps: [HttpClient]
         }
    }),

*最后在模块之外导出 HttpLoaderFactory   
 export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http);
 }
3)引入语言json文件

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  isCollapsed = false;
  constructor(public translate: TranslateService) {
    translate.addLangs(['en', 'zh']);
    translate.setDefaultLang('zh');
    const browserLang = translate.getBrowserLang();
    translate.use(browserLang.match(/en|zh/) ? browserLang : 'en');
  }
}
4)html中使用

{{'app.test' | translate}}
5)页面翻译

引入TranslateService
import { TranslateService } from '@ngx-translate/core';
constructor(private translate: TranslateService) {}
ngOnInit() {
   console.log(this.translate.instant('app.title'))
}

参考:
https://stackblitz.com/edit/github-rvuqkx?file=src%2Fapp%2Fapp.module.ts
https://www.jianshu.com/p/082358d49adc

posted on 2020-09-18 15:22  奇迹般若果  阅读(639)  评论(0编辑  收藏  举报