/
i18n-providers.ts
64 lines (52 loc) · 1.89 KB
/
i18n-providers.ts
1
2
3
4
5
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
31
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
61
62
63
64
import { TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID } from '@angular/core';
import * as moment from 'moment';
declare var navigator: any; // navigator.languages not available yet
export function getTranslationProviders(): Promise<object[]> {
// Make sure a locale exists
ensureLocale();
// Get the locale id from localStorage
const locale = localStorage.getItem('locale');
// return no providers if fail to get translation file for locale
const noProviders: object[] = [];
// No locale or U.S. English: no translation providers
if (!locale || locale === 'en-US') {
return Promise.resolve(noProviders);
}
if (locale.startsWith('de')) {
const translationFileContents = require('raw-loader!../../locale/messages.de.xtb');
return Promise.resolve([
{ provide: TRANSLATIONS, useValue: translationFileContents },
{ provide: TRANSLATIONS_FORMAT, useValue: 'xtb' },
{ provide: LOCALE_ID, useValue: locale }
]);
} else {
return Promise.resolve(noProviders);
}
}
declare var System: any;
function getTranslationsWithSystemJs(file: string) {
return System.import(file + '!text'); // relies on text plugin
}
/**
* This sets the locale depending on the browser configuration.
* The value is extracted from either `navigator.languages[0]`,
* `navigator.language` or `navigator.userLanguage` and persisted to
* localStorage, where all other parts of the application take it from.
*/
function ensureLocale() {
if (!localStorage.getItem('locale')) {
const locale = navigator.languages
? navigator.languages[0]
: (navigator.language || navigator.userLanguage);
localStorage.setItem('locale', locale);
setMomentLocale(locale);
} else {
setMomentLocale(localStorage.getItem('locale'));
}
}
/**
* This sets the locale for all newly create moments globally.
*/
function setMomentLocale(locale: string) {
moment.locale(locale);
}