languages.service.ts 1.51 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
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

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) {
Vitali Stupin's avatar
Vitali Stupin committed
31
      this.translateSubscription = this.translate.get('index.title').pipe(take(1)).subscribe((res: string) => {
Vitali Stupin's avatar
Vitali Stupin committed
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
        this.title.setTitle(res)
      });
    }
  }

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