front end version 2 de framadate, un gestionnaire de sondage
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

68 lines
1.9 KiB

import { Injectable } from '@angular/core';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
import { Language } from '../enums/language.enum';
import { StorageService } from './storage.service';
@Injectable({
providedIn: 'root',
})
export class LanguageService {
constructor(private translate: TranslateService, private storageService: StorageService) {}
public getLangage(): Language {
return this.translate.currentLang as Language;
}
public setLanguage(language: Language): void {
this.translate.use(language.toString());
}
public getAvailableLanguages(): string[] {
return this.translate.getLangs();
}
public configureAndInitTranslations(): void {
// always save in storage the currentLang used
this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
this.storageService.language = event.lang as Language;
});
// set all languages available
this.translate.addLangs(Object.keys(Language));
// set language
this.setLanguageOnInit();
}
private setLanguageOnInit(): void {
// set language from storage
if (!this.translate.currentLang) {
this.setLanguageFromStorage();
}
// or set language from browser
if (!this.translate.currentLang) {
this.setLanguageFromBrowser();
}
// set default language
if (!this.translate.currentLang) {
this.setLanguage(Language.FR);
}
}
private setLanguageFromStorage(): void {
console.log('this.storageService.language', this.storageService.language);
if (this.storageService.language && this.translate.getLangs().includes(this.storageService.language)) {
this.setLanguage(this.storageService.language);
}
}
private setLanguageFromBrowser(): void {
const currentBrowserLanguage: Language = this.translate.getBrowserLang().toUpperCase() as Language;
console.log('currentBrowserLanguage', currentBrowserLanguage);
if (this.translate.getLangs().includes(currentBrowserLanguage)) {
this.setLanguage(currentBrowserLanguage);
}
}
}