update
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { isEmpty } from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class I18nService {
|
||||
|
||||
locale: String;
|
||||
i18n: any;
|
||||
|
||||
constructor(private http: HttpClient) {
|
||||
let browserLocale = navigator.language;
|
||||
|
||||
if (browserLocale.indexOf("-") != -1) {
|
||||
browserLocale = browserLocale.split("-")[0];
|
||||
}
|
||||
|
||||
let locale = localStorage.getItem("bstly.locale") || browserLocale || 'en';
|
||||
|
||||
if (locale == 'de') {
|
||||
locale = 'de-informal';
|
||||
}
|
||||
|
||||
this.setLocale(locale);
|
||||
}
|
||||
|
||||
getLocale() {
|
||||
return this.locale;
|
||||
}
|
||||
|
||||
setLocale(locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
async fetch(locale) {
|
||||
this.i18n = await this.http.get("./assets/i18n/" + locale + ".json").toPromise();
|
||||
}
|
||||
|
||||
get(key, args: any[]): String {
|
||||
return this.getInternal(key, args, this.i18n);
|
||||
}
|
||||
|
||||
getInternal(key, args: any[], from): String {
|
||||
if (!from) {
|
||||
return key;
|
||||
} else if (from[key]) {
|
||||
if (from[key]["."]) {
|
||||
return this.insertArguments(from[key]["."], args);
|
||||
}
|
||||
return this.insertArguments(from[key], args);
|
||||
} else {
|
||||
let keys = key.split(".");
|
||||
if (from[keys[0]]) {
|
||||
key = keys.slice(1, keys.length).join(".");
|
||||
return this.getInternal(key, args, from[keys[0]])
|
||||
}
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
insertArguments(label: String, args: any[]) {
|
||||
if (args) {
|
||||
for (let index in args) {
|
||||
label = label.replace(`{${index}}`, args[index]);
|
||||
}
|
||||
}
|
||||
return label;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user