mempool/frontend/src/app/services/language.service.ts

41 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-01-12 13:24:20 +09:00
import { DOCUMENT, getLocaleId } from '@angular/common';
import { LOCALE_ID, Inject, Injectable } from '@angular/core';
import { languages } from 'src/app/app.constants';
@Injectable({
providedIn: 'root'
})
export class LanguageService {
private language = 'en';
private languages = languages;
constructor(
@Inject(DOCUMENT) private document: Document,
2022-01-12 13:24:20 +09:00
@Inject(LOCALE_ID) private locale: string,
2022-01-12 19:08:56 +04:00
) {
this.language = getLocaleId(this.locale).substring(0, 2);
}
getLanguage(): string {
2022-01-12 19:08:56 +04:00
return this.language;
}
2022-01-12 13:24:20 +09:00
stripLanguageFromUrl(urlPath: string) {
let rawUrlPath = urlPath ? urlPath : document.location.pathname;
const urlLanguage = this.document.location.pathname.split('/')[1];
2022-01-12 13:24:20 +09:00
if (this.languages.map((lang) => lang.code).indexOf(urlLanguage) != -1) {
rawUrlPath = rawUrlPath.substring(3);
}
2022-01-12 13:24:20 +09:00
return rawUrlPath;
}
getLanguageForUrl(): string {
2022-01-12 19:08:56 +04:00
return this.language === 'en' ? '' : '/' + this.language;
}
setLanguage(language: string): void {
try {
document.cookie = `lang=${language}; expires=Thu, 18 Dec 2050 12:00:00 UTC; path=/`;
} catch (e) { }
}
}