Data Initialization
In general, for most of the products, it’s good enough to load all translations and patterns one time in root module when the application starts, but for some special requirements, such like: isolated translation for feature module or using lazy module to enhance performance, please refer to Isolated feature module and Lazy Load Module. singleton client provides two ways to load i18n data and initialize the services in root module:
Blocking loading
For preloading modules - Create a factory function that loads i18n resource data and provide that function to the APP_INITIALIZER token. The function is executed during the application bootstrap process, and the needed data is available on startup.
export function initVIPConfig(vipService: VIPService, localeService: LocaleService) {
// Specify locale, either from browser language or user's profile.
const currentlocale: string = getBrowserCultureLang();
localeService.init(currentlocale);
return () => vipService.initData(I18nConfig);
}
@NgModule({
...
imports: [
...
HttpClientModule,
VIPModule.forRoot(),
...
],
providers: [{
provide: APP_INITIALIZER,
useFactory: initVIPConfig,
deps: [
VIPService,
LocaleService
],
multi: true
}],
...
})
export class AppModule {}
For lazy-loading modules - Configure i18nDataGuard as part of the route object to load i18n resource for a lazy-loading module by reading lite Singleton configuration from route parameters, asynchronously load the data, and have it ready by the time the module activates and initializes.
const routes: Routes = [
{
path: '',
component: SampleComponent,
canActivate: [I18nDataGuard],
data: {
// 'vipConfig' is specified keyword of Singleton configuration.
// In the simplified configuration of lazy loading module,
// only the component name is required, and other fields are optional.
vipConfig: {
component: 'sample',
sourceBundles: [ENGLISH]
}
}
}
]
Non-blocking loading
Whether it is preloading modules or lazy-loading modules, in addition to loading data in a blocking way, you can also use a non-blocking way.
Note that since data is loaded in a non-blocking way, when calling synchronous ‘getMessage’ or data formatting-related methods, be sure to use these synchronous methods safely by subscribing to the ‘stream’ API.
// app.module.ts
export class AppModule {
constructor( vipService: VIPService, localeService: LocaleService ) {
const currentlocale: string = getBrowserCultureLang();
localeService.init(currentlocale);
vipService.initData(I18nConfig);
}
}
// lazy.module.ts
export class LazyModule {
constructor(private service: VIPService) {
// In the simplified configuration of lazy loading module,
// only the component name is required, and other fields are optional.
service.initLazyModuleData({
component: 'default',
sourceBundles: [ENGLISH]
});
}
}