import 'rxjs/add/operator/toPromise'; export class Dictionary { private dictionary; private dictionaryURL = '/assets/i18n'; private http; private i18nService; private componentDictionaries = {}; constructor(http, i18nService) { this.http = http; this.i18nService = i18nService; this.setDictionary(); } lookup(path: string, language: string, componentName?: string): any { let value = this.getChainedValue(path, componentName); return value; } setDictionaryURL(path: string): Promise { this.dictionaryURL = path; return this.setDictionary(); } setDictionary(): Promise { let language = this.i18nService.getLanguageId(); return this.http.get(this.dictionaryURL + '/' + language + '.json') .toPromise() .then(response => { this.dictionary = response.json(); }) .catch(this.handleError); } setComponentDictionaryURL(path: string, componentName: string): Promise { let language = this.i18nService.getLanguageId(); // dictionary for component will NOT be reset if path or locale was NOT changed if (this.componentDictionaries[componentName] && this.componentDictionaries[componentName].dictionaryURL == path && this.componentDictionaries[componentName].dictionaryLocale == language) { return Promise.resolve(); } // download dictionary return this.http.get(path + '/' + language + '.json') .toPromise() .then(response => { this.componentDictionaries[componentName] = { dictionaryLocale: language, dictionaryURL: path, dictionary: response.json() } }) .catch(this.handleError); } private handleError(error: any): Promise { return Promise.reject(error.message || error); } private getChainedValue(path: string, componentName?: string): any { var schema = this.dictionary, pList = path.split('.'); // look in component dictionary if component name is provided if (componentName) { if (this.componentDictionaries[componentName] && this.componentDictionaries[componentName].dictionary) { schema = this.componentDictionaries[componentName].dictionary; } else { return ''; } } // lookup mechanism itsef for (var i = 0; i < pList.length; i++) { var elem = pList[i]; if (!schema[elem] && schema[elem] !== '' && schema[elem] !== false) { schema[elem] = ''; } schema = schema[elem]; } return schema; } }