资料来源: 

GitHub - ngx-translate/core: The internationalization (i18n) library for Angular

第一步 安装核心translate/core

在创建好的项目中安装 @ngx-translate/core

npm install @ngx-translate/core --save

第二步 安装http-loader

继续安装 @ngx-translate/http-loader

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

备注: 在较新的包(nodejs)时,无需添加 --save 参数

第三步 导入到app.module

修改app.module.ts, 添加关于 翻译所需要的代码

添加

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

以及

TranslateModule.forRoot({
      defaultLanguage: 'zh',
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),

使得效果如下 

registerLocaleData(zh);
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    TranslateModule.forRoot({
      defaultLanguage: 'zh',
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    IconsProviderModule,
    NzLayoutModule,
    NzMenuModule
  ],
  providers: [

    { provide: NZ_I18N, useValue: zh_CN },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptorService,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

第四步 创建翻译文件

在assets目录创建所需的文件, 这里包含了英文,日文和中文。

可以在之前的代码中找到对应,默认的语言是'zh',所以你也需要创建 zh.json.

实际上多个语言的 zh 对应 zh.json

jp 对应jp.json

等等。

第五步 导入翻译模块到组件或者模块

我们先试试默认的语言

zh.json

{
  "chat-history": {
    "new-chat": "新的聊天",
    "settings": "设置",
    "prompts": "预设",
    "delete": "删除"
  }
}

在独立组件(standalone=true)或者模块中导入 TranslateModule 

第六步 使用管道来使用翻译

然后再html模版中使用管道

动态属性使用法

[nzTitle]="'chat-history.new-chat' | translate"

插值使用法

{{ 'chat-history.new-chat' | translate}}

其中的chat-history.new-chat就像是读取json的属性一样,可以多层,也可以只有一层。

可以看看效果咯

第七步 切换语言

只需要注入TranslateService,并使用use修改语言即可。

当然,如果想要实现合理的逻辑,还需要进行一些 可持续存储操作,以及读取配置等。

constructor(translate: TranslateService) {
        // this language will be used as a fallback when a translation isn't found in the current language
        translate.setDefaultLang('en');

         // the lang to use, if the lang isn't available, it will use the current loader to get them
        translate.use('en');
    }

更多

除了使用管道,还有更多的使用方法和细节,但是管道这个初级用法可以覆盖90%以上的多语言支持,更多细节,请查看头部的链接,阅读文档。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐