Translation Angular 2 using ngx-translate?

2019-02-16 03:19发布

I have all configuration and setting following instructions.

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.

There are not any errors in console. Why ngx-translate does not work or what I do wrong.

2条回答
Explosion°爆炸
2楼-- · 2019-02-16 04:02

if you're still on Angular <4.3, please use Http from @angular/http with 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

查看更多
乱世女痞
3楼-- · 2019-02-16 04:20

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. 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:

// 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:

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

component.ts:

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

export class Component{

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

component.html:

{{ 'Intro' | translate }}
查看更多
登录 后发表回答