Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular: LOCATION_INITIALIZED what is it and why use it?

Tags:

angular

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?

like image 559
Arikael Avatar asked May 09 '18 09:05

Arikael


1 Answers

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);
        });
});

}

like image 77
Emanuele Fricano Avatar answered Sep 25 '22 05:09

Emanuele Fricano