languages.service.ts 1.51 KB
Newer Older
Vitali Stupin's avatar
Vitali Stupin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { Injectable } from '@angular/core';
import {TranslateService} from "@ngx-translate/core";
import { Title } from '@angular/platform-browser';
import { Subscription } from 'rxjs';

const LANGUAGES = {
  'EST': 'est',
  'ENG': 'eng'
}

@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) {
      this.translateSubscription = this.translate.get('index.title').subscribe((res: string) => {
        this.title.setTitle(res)
        this.translateSubscription.unsubscribe()
      });
    }
  }

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

  getLang(): string {
    return this.selectedLang
  }

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

  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()
  }
}