Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Last active March 3, 2021 08:54
Show Gist options
  • Save bartwttewaall/8b04981fe0e050799a18b454368e2952 to your computer and use it in GitHub Desktop.
Save bartwttewaall/8b04981fe0e050799a18b454368e2952 to your computer and use it in GitHub Desktop.
Quick and dirty translation service in Angular
import { Injectable } from '@angular/core';
import { STRING_MESSAGES } from '../components/comet-chat-components/utils/messageConstants';
import { DA_MESSAGES } from '../i18n/da';
import { DE_MESSAGES } from '../i18n/de';
import { EN_MESSAGES } from '../i18n/en';
import { ES_MESSAGES } from '../i18n/es';
import { FR_MESSAGES } from '../i18n/fr';
import { HU_MESSAGES } from '../i18n/hu';
import { IT_MESSAGES } from '../i18n/it';
import { NL_MESSAGES } from '../i18n/nl';
import { NO_MESSAGES } from '../i18n/no';
import { PT_MESSAGES } from '../i18n/pt';
import { SL_MESSAGES } from '../i18n/sl';
import { SV_MESSAGES } from '../i18n/sv';
interface HashTable<T> {
[key: string]: T;
}
@Injectable({
providedIn: 'root',
})
export class LangService {
private _defaultLang: string = 'en';
private _currentLang: string = 'en';
private translations: { [key: string]: HashTable<string> };
private fallback: HashTable<string> = STRING_MESSAGES;
get defaultLang(): string {
return this._defaultLang;
}
get currentLang(): string {
return this._currentLang;
}
get languages(): string[] {
return Object.keys(this.translations);
}
constructor() {
this.translations = {
da: DA_MESSAGES,
de: DE_MESSAGES,
en: EN_MESSAGES,
es: ES_MESSAGES,
fr: FR_MESSAGES,
hu: HU_MESSAGES,
it: IT_MESSAGES,
nl: NL_MESSAGES,
no: NO_MESSAGES,
pt: PT_MESSAGES,
sl: SL_MESSAGES,
sv: SV_MESSAGES,
};
}
setDefaultLang(lang: string) {
this._defaultLang = lang.toLowerCase();
}
use(lang: string) {
if (this.languages.includes(lang.toLowerCase())) this._currentLang = lang;
}
trans(key, fallbackValue: string = undefined) {
let source = this.translations[this.currentLang];
if (source.hasOwnProperty(key)) return source[key];
source = this.translations[this.defaultLang];
if (source.hasOwnProperty(key)) return source[key];
source = this.fallback;
if (source.hasOwnProperty(key)) return source[key];
return fallbackValue || key;
}
resolveLocale(url: string, segmentIndex: number, defaultLanguage = 'en') {
// look for either ISO 3166-1 alpha-2 or combined with ISO 3166-2
const pattern = /\b\w{2}(-\w{2})?\b/gim;
const segments = url.split('/');
return segmentIndex < segments.length && pattern.test(segments[segmentIndex]) ? segments[segmentIndex] : defaultLanguage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment