Angular 4 Ngx-translate pipe not working

2019-04-14 04:06发布

问题:

I want to make an angular 4 app that is multilangual. I have followed the answer on Angular 2 - Multilingual Support but it doesn't work.

I did every step, from 1 to 5 on that page and my appmodule looks the same.

I have a file en.json in a folder i18n, located in my assets folder. The file contains

{ "TEST":"little test"}

and in my HTML:

 <a [routerLink]="['/home']" class="tile waves-effect waves-light btn-large">
  <span> {{ "TEST" | translate }}</span>
 </a>

And when I use it I get TEST instead of little test. This is really annoying because I want to add multiple languages.

edit
I've added this code to my appmodule.ts (only necessary added)

import {HttpClientModule, HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';

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

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    MaterializeModule.forRoot(),
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    FormsModule,
    JsonpModule,
    routing,
    BrowserAnimationsModule,
  ],

回答1:

Could you try like this?

export function HttpLoaderFactory(http: Http) { return new TranslateHttpLoader(http, "./assets/i18n/", ".json"); }



回答2:

First import traslate service to featured module. Inside module constructor use:

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