Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make sure translations JSON file has loaded before continuing to load Angular app

We're using ng2-translate to implement internationalisation in an Angular application, with translations using the .instant(...) method to avoid the clutter of subscribing to observables.

However, .instant will error if the translations JSON file hasn't finished loading yet. Is there a way to wait until the translations file is finished downloading before continuing to load the rest of the app?

like image 791
Transmission Avatar asked Dec 05 '22 00:12

Transmission


2 Answers

Maybe you can try to initialize a default language translation at the angular app startup.

Add this in your app.module.ts

providers: [
  {
    provide: APP_INITIALIZER,
    useFactory: appInitializerFactory,
    deps: [TranslateService],
    multi: true
  }
]


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

export function appInitializerFactory(translate: TranslateService) {
  return () => {
    translate.setDefaultLang('es');
    return translate.use('es').toPromise();
  };
}

You can find more details here: https://mcvendrell.medium.com/configuring-ngx-translate-to-load-at-startup-in-angular-1995e7dd6fcc

like image 94
user739DamQ Avatar answered Dec 09 '22 13:12

user739DamQ


The doc explicitly say for instant : Gets the instant translated value of a key (or an array of keys). /!\ This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead.

Also, please note that you can't block angular initialisation. The angular team does NOT want you to be able to do that.

I read the code of the lib, and the use method will return you an observable anyway. So your best shot is to do in your code (given the doc example code since you didn't posted yours :

constructor(translate: TranslateService) {
    var userLang = navigator.language.split('-')[0]; // use navigator lang if available
    userLang = /(fr|en)/gi.test(userLang) ? userLang : 'en';

    // this language will be used as a fallback when a translation isn't found in the current language
    translate.setDefaultLang('en');

    // the lang to use, if the lang isn't available, it will use the current loader to get them
    /* Here is your observable */
    translate
        .use(userLang)
        .subscribe(res: any => 
        {
            // In here you can put the code you want. At this point the lang will be loaded
        });
}

So in the subscribe callback you can do whatever you want, given that the lang is load at this point. I can't help you more since you didn't posted code but if you need further help let me now.

like image 29
Adam S Avatar answered Dec 09 '22 15:12

Adam S