languages.service.ts 1.5 KB
Newer Older
Vitali Stupin's avatar
Vitali Stupin committed
1 2 3 4
import { Injectable } from '@angular/core';
import {TranslateService} from "@ngx-translate/core";
import { Title } from '@angular/platform-browser';
import { Subscription } from 'rxjs';
Vitali Stupin's avatar
Vitali Stupin committed
5
import { take } from 'rxjs/operators';
Vitali Stupin's avatar
Vitali Stupin committed
6
import { LANGUAGES } from './config'
Vitali Stupin's avatar
Vitali Stupin committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

@Injectable({
  providedIn: 'root'
})
export class LanguagesService {
  private selectedLang = ''
  private translateSubscription: Subscription
  
  constructor(
    private translate: TranslateService,
    private title: Title
  ) {
    this.selectedLang = this.getDefaultLang()
    translate.setDefaultLang(LANGUAGES[this.selectedLang])
    this.updateTitle()
  }

  updateTitle(): void {
    // Not subscribing if subscription already in progress
    if (!this.translateSubscription || this.translateSubscription.closed) {
Vitali Stupin's avatar
Vitali Stupin committed
27
      this.translateSubscription = this.translate.get('index.title').pipe(take(1)).subscribe((res: string) => {
Vitali Stupin's avatar
Vitali Stupin committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
        this.title.setTitle(res)
      });
    }
  }

  getDefaultLang(): string {
    if(window && window.localStorage && window.localStorage.getItem('lang')) {
      return window.localStorage.getItem('lang')
    }
    return Object.keys(LANGUAGES)[0]
  }

  getLangs(): string[] {
    return Object.keys(LANGUAGES)
  }

Vitali Stupin's avatar
Vitali Stupin committed
44 45 46 47
  getLang(): string {
    return this.selectedLang
  }

Vitali Stupin's avatar
Vitali Stupin committed
48 49 50 51 52 53 54 55 56
  setLang(lang: string): void {
    this.selectedLang = lang
    if(window && window.localStorage) {
      window.localStorage.setItem('lang', this.selectedLang)
    }
    this.translate.use(LANGUAGES[this.selectedLang]);
    this.updateTitle()
  }
}