简体   繁体   English

使用ngx-translate翻译Angular 2?

[英]Translation Angular 2 using ngx-translate?

I have all configuration and setting following instructions. 我已经按照以下说明进行了所有配置和设置。

app.module.ts app.module.ts

import {  Http } from '@angular/http';
import {TranslateModule, TranslateStaticLoader, TranslateLoader, TranslateService } from 'ng2-translate';

imports: [
    BrowserModule,
    HttpModule,
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
      deps: [Http]
    })
]

Component: 零件:

import {TranslateService,TranslatePipe } from 'ng2-translate';

constructor( private activateRoute: ActivatedRoute, public translate: TranslateService) {
    translate.addLangs(['en']);
    translate.setDefaultLang('en');

  }

And view component: 并查看组件:

{{ 'Intro' | translate }}

This library does not work for me, it alwsays displays key of word Intro instead value translations. 该库对我不起作用,它总是显示单词Intro关键字,而不是值翻译。

There are not any errors in console. 控制台中没有任何错误。 Why ngx-translate does not work or what I do wrong. 为什么ngx-translate不起作用或我做错了什么。

Looking at your code can't really tell what's not working. 查看您的代码无法真正分辨出什么无效。 One difference I noticed is, I did my setup using HttpLoaderFactory provided by ngx-translate doc . 一个区别我注意到的是,我用做了我的设置HttpLoaderFactory提供ngx-translate 文档 I'll provide my full setup and you can compare it with your code, if it helps to detect any issues :) 我将提供完整的设置,如果可以帮助您发现任何问题,您可以将其与代码进行比较:)

Setup: 设定:

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

app.module.ts: app.module.ts:

// i18n library
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

@NgModule({
  ...
  imports: [
    ...
    TranslateModule.forRoot({
      loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [Http]
      }
    })
  ]

src > assets > i18n > en.json: src>资产> i18n> en.json:

{
  "Intro" : "This is intro!"
}

component.ts: component.ts:

import { TranslateService } from '@ngx-translate/core';

export class Component{

  constructor(translate: TranslateService){
    this.translate.setDefaultLang('en');
  }
}

component.html: component.html:

{{ 'Intro' | translate }}

if you're still on Angular <4.3, please use Http from @angular/http with http-loader@0.1.0. 如果您仍使用Angular <4.3,请使用@ angular / http中的Http和http-loader@0.1.0。

so running 这么跑

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

did the trick for me 为我做了把戏

Source: ngx-translate/core 资料来源: ngx-translate / core

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM