通过将 BehaviorSubject 添加到 JhiLanguageHelper 服务,我设法修复了延迟加载模块中的翻译。
@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');
}
}
然后您像这样订阅模块中的 BehaviorSubject。
export class YourModule {
constructor(private languageService: JhiLanguageService, private languageHelper: JhiLanguageHelper) {
this.languageHelper.language.subscribe((languageKey: string) => this.languageService.changeLanguage(languageKey));
}
}