简体   繁体   中英

Ngx-translate with Angular Universal

I just upgraded from ng2-translate ( v. 5.xx ) to ngx-translate ( v. 6.xx ) in my Angular 2 Universal App.

Before the upgrade I was using this loader ( found here ):

class TranslateUniversalLoader implements TranslateLoader {
  public getTranslation(lang: string): Observable<any> {
    return Observable.create(observer => {
      observer.next(JSON.parse(fs.readFileSync(`src/i18n/${lang}.json`, 'utf8')));
      observer.complete();
    });
  }
}

That I was using like so:

@NgModule({
  bootstrap: [AppComponent],
  declarations: [ AppComponent ],
  imports: [
    FormsModule,
    CoreModule,
    ViewsModule,
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useClass: TranslateUniversalLoader,
    }),
    UniversalModule
  ]
})

After upgrading to ngx-translate , however, I get this error in the terminal console (thus, server-side error):

Module build failed: Error: /src/app/app.node.module.ts (65,7): 
Argument of type '{ provide: typeof TranslateLoader; useClass: typeof TranslateUniversalLoader; }' is not assignable to parameter of type 'TranslateModuleConfig'.

So anyone knows how to set up a custom loader for server side support with Angular Universal with ngx-translate ?

The solution was way easier than expected and detailed in the migration guide .

In 6.xx what is changed that was breaking the code is the expected value passed to forRoot() .

Now we need to pass the loader as an object of the loader key, like so:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useClass: TranslateUniversalLoader,
  }
}),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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