angulartypescriptangular8angular-translate

Translate service not working on load page


I have a very strange behaviour when using translate service. I configure the translator like this :

export class AppComponent implements OnInit {


constructor(
    private translateService: TranslateService,
    angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics,
    angulartics2: Angulartics2,
    router: Router,
    private googleAnalyticsService: GoogleAnalyticsService,
) {
     translateService.setDefaultLang('en');
     translateService.use('en');
}

And My HomeComponent :

export class HomePageComponent implements OnInit {
constructor(
    private seoService: SeoService,
    private translateService: TranslateService
) {
}

ngOnInit() {
    this.addPageMeta();
    console.log('Add Page Meta');
}

addPageMeta() {
const title = this.translateService.instant('seo.home.title');
const meta: SeoMeta = {
  url : '/home',
  title: title,
  description: this.translateService.instant('seo.home.description'),
};
this.seoService.setPageTitle(title);
this.seoService.addMeta(meta);
}
}

Core.module.ts :

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: HttpLoaderFactory,
    deps: [HttpClient]
  }
})
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

When I do a refresh I have in title of my page seo.home.title so the translation is not done, after that if I swith to another page, after that back to homepage, translations is working. If again a do an F5 translation didn't work. And this problem is everywhere when I load first time page.

Thanks in advance.


Solution

  • you can preload default language with application initializer as follow

    translation.config.ts

    import { Injector } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    import { LOCATION_INITIALIZED } from '@angular/common';
    import { TranslateService } from '@ngx-translate/core';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    
    export function HttpLoaderFactory(httpClient: HttpClient) {
      return new TranslateHttpLoader(httpClient);
    }
    
    export function ApplicationInitializerFactory(
      translate: TranslateService, injector: Injector) {
      return async () => {
        await injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
    
        const deaultLang = 'fr';
        translate.addLangs(['en', 'fr']);
        translate.setDefaultLang(deaultLang);
        try {
          await translate.use(deaultLang).toPromise();
        } catch (err) {
          console.log(err);
        }
        console.log(`Successfully initialized ${deaultLang} language.`);
      };
    }
    

    app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule, APP_INITIALIZER, Injector } from '@angular/core';
    import { HttpClient, HttpClientModule } from '@angular/common/http';
    
    import {TranslateModule, TranslateService, TranslateLoader} from '@ngx-translate/core';
    import { ApplicationInitializerFactory, HttpLoaderFactory } from './translation.config';
    
    import { FormsModule } from '@angular/forms';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [ HttpClient ]
          }
        })
      ],
      providers: [
        {
          provide: APP_INITIALIZER,
          useFactory: ApplicationInitializerFactory,
          deps: [ TranslateService, Injector ],
          multi: true
        },
      ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule { }
    

    link to example