I stumbled upon LOCATION_INITIALIZED
when researching loading ngx-translate translations in APP_INITIALIZER
(see enter link description here
import { Injector, APP_INITIALIZER } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { LOCATION_INITIALIZED } from '@angular/common';
export function appInitializerFactory(translate: TranslateService, injector: Injector) {
return () => new Promise<any>((resolve: any) => {
const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
locationInitialized.then(() => {
const langToSet = 'en-GB'
translate.setDefaultLang('en-US');
translate.use(langToSet).subscribe(() => {
console.info(`Successfully initialized '${langToSet}' language.'`);
}, err => {
console.error(`Problem with '${langToSet}' language initialization.'`);
}, () => {
resolve(null);
});
});
});
}
According to angular's source code it's when, in my case, the browser (platform) is ready (DOM, Location and History is ready, would be my guess).
Unfortunately it's not really documented anywhere.
I used the example above without LOCATION_INITIALIZED
and it worked as expected.
So why should I care about LOCATION_INITIALIZED
and when should I use it?
I used the same code to initialize safely the ngx-translate translations in order to use instant method of the Translate service and I had the same doubt.
Anyway, searching online and according to the documentation for the APP_INITIALIZER we just need to provide our function(s) that will be executed during app init (using a promise initialization does not complete until the Promise is resolved).
So yes, you can get rid of the LOCATION_INITIALIZED and use this function for instance ( I am using it and it is working fine).
export function appInitializerTranslationsFactory(translate: TranslateService) {
return () => new Promise<any>((resolve: any) => {
const langToSet = 'en';
translate.setDefaultLang('en');
translate.use(langToSet).subscribe(() => {}, err => {}, () => {
resolve(null);
});
});
}
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