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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With