Angular4中的I18N问题

来源:互联网 发布:数组在内存中如何存储 编辑:程序博客网 时间:2024/06/16 03:20

这篇博客是转载的,因为自己的项目需要进行国际化,这篇教程是我找的写得比较好的文章,分享给大家。

(1)npm 安装 ngx-translate 模块

npm install @ngx-translate/core --savenpm install @ngx-translate/http-loader --save

(2)在 Angular 项目配置

  • 修改app.module.ts
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { HttpModule, Http } from '@angular/http';import { TranslateLoader, TranslateModule} from '@ngx-translate/core';import { TranslateHttpLoader } from '@ngx-translate/http-loader';import { AppComponent } from './app.component';export function createTranslateHttpLoader(http: Http) {    return new TranslateHttpLoader(http, './assets/i18n/', '.json');}@NgModule({ declarations: [      AppComponent ], imports: [    BrowserModule,    HttpModule,    TranslateModule.forRoot({        loader: {            provide: TranslateLoader,            useFactory: (createTranslateHttpLoader),            deps: [Http]         }     }) ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
  • 修改app.component.ts
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 {  title = 'app';  constructor(public translateService: TranslateService) {} ngOnInit() {     // --- set i18n begin ---     this.translateService.addLangs(["zh", "en"]);     this.translateService.setDefaultLang("zh");     const browserLang = this.translateService.getBrowserLang();     this.translateService.use(browserLang.match(/zh|en/) ? browserLang : 'zh');     // --- set i18n end ---  }}
  • 添加多语言文件
    在 src/app/assets/ 下创建 i18n 文件夹,并在文件夹内创建 en.json 和 zh.json 文件

 --> assets    --> i18n         --> en.json         --> zh.json

(3)测试

  • app.component.html
 <div> <span> test the i18n module: ngx-translate</span> <h1>{{ 'hello' | translate }}</h1></div>
  • 在 en.json 和 zh.json 文件中添加配置
    en.json
{ "hello": "the word is hello"}

zh.json

{ "hello": "你好"}

总结

如果你的在安装上面的插件是出了问题,一般是版本的问题,因为你若不指明具体的版本号npm默认下载的是最新的版本,而最新版本可能会出现不兼容的问题,这是你可以尝试安装老的版本,比如:

npm install @ngx-translate/core@7.2.2 --savenpm install @ngx-translate/http-loader@0.1.0 --save

这种方法的缺点就是每次你一更新你的页面比如新添加某一个字你就得手动在en.json和zh.json这两个文件进行修改,少一点还可以接受,要是多了,那工作量很大;但目前也只能这样做,如果你有更好的解决办法欢迎留言探讨。

原创粉丝点击