Skip to content

Instantly share code, notes, and snippets.

@DamienBraillard
Created November 2, 2018 16:56
Show Gist options
  • Save DamienBraillard/eb928ff78141ec05cd5dfe0706070f17 to your computer and use it in GitHub Desktop.
Save DamienBraillard/eb928ff78141ec05cd5dfe0706070f17 to your computer and use it in GitHub Desktop.
ngx-translate
const languages = ['en', 'fr'];
this.translateService.addLangs(languages);
for (const lang of languages) {
this.translateService.setTranslation(lang, require('../assets/i18n/' + lang + '.json'));
}
// Set this after 'setTranslation' to avoid unnecessary XHR request
this.translateService.setDefaultLang('en');
const browserLang = this.translateService.getBrowserLang();
this.translateService.use(languages.includes(browserLang) ? browserLang : 'en');
import {TranslateLoader} from '@ngx-translate/core';
import {HttpClient} from "@angular/common/http";
import 'rxjs/add/operator/map';
// Translation loader that skips enpty translations so that the key is displayed instead !
// Based on the HTTP loader implementation.
export class PruningTranslationLoader implements TranslateLoader {
constructor(private http: HttpClient, private prefix: string = '/assets/i18n/', private suffix: string = '.json') {
}
public getTranslation(lang: string): any {
return this.http.get(`${this.prefix}${lang}${this.suffix}`)
.map((res: Object) => this.process(res));
}
private process(object: any) {
const newObject = {};
for (const key in object) {
if (object.hasOwnProperty(key)) {
if (typeof object[key] === 'object') {
newObject[key] = this.process(object[key]);
}
else if ((typeof object[key] === 'string') && (object[key] === '')) {
// do not copy empty strings
}
else {
newObject[key] = object[key];
}
}
}
return newObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment