language.helper.ts 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { Injectable, RendererFactory2, Renderer2 } from '@angular/core';
  2. import { Title } from '@angular/platform-browser';
  3. import { Router, ActivatedRouteSnapshot } from '@angular/router';
  4. import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
  5. import { BehaviorSubject, Observable } from 'rxjs';
  6. import { LANGUAGES } from 'app/core/language/language.constants';
  7. @Injectable({ providedIn: 'root' })
  8. export class JhiLanguageHelper {
  9. renderer: Renderer2 = null;
  10. private _language: BehaviorSubject<string>;
  11. constructor(
  12. private translateService: TranslateService,
  13. // tslint:disable-next-line: no-unused-variable
  14. private rootRenderer: RendererFactory2,
  15. private titleService: Title,
  16. private router: Router
  17. ) {
  18. this._language = new BehaviorSubject<string>(this.translateService.currentLang);
  19. this.renderer = rootRenderer.createRenderer(document.querySelector('html'), null);
  20. this.init();
  21. }
  22. getAll(): Promise<any> {
  23. return Promise.resolve(LANGUAGES);
  24. }
  25. get language(): Observable<string> {
  26. return this._language.asObservable();
  27. }
  28. /**
  29. * Update the window title using params in the following
  30. * order:
  31. * 1. titleKey parameter
  32. * 2. $state.$current.data.pageTitle (current state page title)
  33. * 3. 'global.title'
  34. */
  35. updateTitle(titleKey?: string) {
  36. if (!titleKey) {
  37. titleKey = this.getPageTitle(this.router.routerState.snapshot.root);
  38. }
  39. this.translateService.get(titleKey).subscribe(title => {
  40. this.titleService.setTitle(title);
  41. });
  42. }
  43. private init() {
  44. this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
  45. this._language.next(this.translateService.currentLang);
  46. this.renderer.setAttribute(document.querySelector('html'), 'lang', this.translateService.currentLang);
  47. this.updateTitle();
  48. });
  49. }
  50. private getPageTitle(routeSnapshot: ActivatedRouteSnapshot) {
  51. let title: string = routeSnapshot.data && routeSnapshot.data['pageTitle'] ? routeSnapshot.data['pageTitle'] : 'zipConnectApp';
  52. if (routeSnapshot.firstChild) {
  53. title = this.getPageTitle(routeSnapshot.firstChild) || title;
  54. }
  55. return title;
  56. }
  57. }