i18n在JHipster应用程序中加载了懒惰的组件

时间:2017-06-29 14:34:23

标签: angular jhipster ngx-translate

My App基于JHipster,因此ng-jhipster库中JhiLanguageService提供的语言服务使用JhiConfigService来配置this idea {1}}我无需导入和配置ngx-translate中的TranslateModule。因此,当我向AppModule的导入添加app.module时,一切都会中断,我只看到"翻译未找到..."消息无处不在。

我不知道如何让我的延迟加载的页面使用与应用程序的急切加载部分相同的翻译服务实例,以便在导航栏的热切加载的组件中更改语言会影响延迟加载页面使用的语言。

我已经研究过this ideaSee the Documentation here for more details,但是他们都规定在AppModule中配置TranslateModule会打破它,我不知道如何在JHipster应用程序中控制ngx-translate配置。< / p>

1 个答案:

答案 0 :(得分:1)

我通过将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));
    }
}