My App is based on JHipster and so the language services are provided by way of JhiLanguageService in the ng-jhipster
library which uses a JhiConfigService to c
I managed to fix translation in my lazy loaded module by adding BehaviorSubject to the JhiLanguageHelper service.
@Injectable()
export class JhiLanguageHelper {
renderer: Renderer2 = null;
private _language: BehaviorSubject<string>;
constructor(
private translateService: TranslateService,
private rootRenderer: RendererFactory2,
private findLanguageFromKeyPipe: FindLanguageFromKeyPipe,
private titleService: Title,
private router: Router
) {
this._language = new BehaviorSubject<string>(this.translateService.currentLang);
this.renderer = rootRenderer.createRenderer(document.querySelector('html'), null);
this.init();
}
getAll(): Promise<any> {
return Promise.resolve(LANGUAGES);
}
get language(): Observable<string> {
return this._language.asObservable();
}
updateTitle(titleKey?: string) {
if (!titleKey) {
titleKey = this.getPageTitle(this.router.routerState.snapshot.root);
}
this.translateService.get(titleKey).subscribe((title) => {
this.titleService.setTitle(title);
});
}
private init() {
this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
this._language.next(this.translateService.currentLang);
this.renderer.setAttribute(document.querySelector('html'), 'lang', this.translateService.currentLang);
this.updateTitle();
this.updatePageDirection();
});
}
private getPageTitle(routeSnapshot: ActivatedRouteSnapshot) {
let title: string = (routeSnapshot.data && routeSnapshot.data['pageTitle']) ? routeSnapshot.data['pageTitle'] : 'hcmGatewayApp';
if (routeSnapshot.firstChild) {
title = this.getPageTitle(routeSnapshot.firstChild) || title;
}
return title;
}
private updatePageDirection() {
this.renderer.setAttribute(document.querySelector('html'), 'dir', this.findLanguageFromKeyPipe.isRTL(this.translateService.currentLang) ? 'rtl' : 'ltr');
}
}
And you subscribe to the BehaviorSubject in your module like this.
export class YourModule {
constructor(private languageService: JhiLanguageService, private languageHelper: JhiLanguageHelper) {
this.languageHelper.language.subscribe((languageKey: string) => this.languageService.changeLanguage(languageKey));
}
}