Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
code-split ng2-translate

note

This was implemented back in like angular2-beta.3, and the branch has been abandoned

The gist is really doing the async loading of the other language file prior to activating the lazy-loaded route/component. At the time it was an @CanActivate annotation, but now could probably be done in a router guard.

App setup is normal https://github.com/ocombe/ng2-translate

import {TranslateService} from 'ng2-translate/ng2-translate';
import {Http} from 'angular2/http';
import {Router, CanActivate, ComponentInstruction} from 'angular2/router';
import {I18nHelper} from './i18n-helper';
/* tells you how old this is: beta.3 @CanActivate DI workaround. (IGNORE) */
// workaround dependencies since @CanActivate doesn't have DI access yet (as of 2/1/2016).
// See https://github.com/angular/angular/issues/4112
// and http://plnkr.co/edit/SF8gsYN1SvmUbkosHjqQ?p=preview
import {Injector} from 'angular2/core';
import {appInjector} from '../../app-injector';
export const ensureTranslationReady = (to: ComponentInstruction,
from: ComponentInstruction, moduleName: String) => {
let injector: Injector = appInjector(); // get the stored reference to the injector
let i18nHelper: I18nHelper = injector.get(I18nHelper);
let translate = injector.get(TranslateService);
let http = injector.get(Http);
let lang = translate.currentLang;
let pathToAssets: String = '../../../assets/i18n/';
let fileName = `${lang}-${moduleName}.json`;
let path = `${pathToAssets}${fileName}`;
// return a boolean or a promise that resolves a boolean
return new Promise((resolve) => {
if (i18nHelper.isAlreadyLoaded(path)) {
// TranslateService has it cached. Don't load it again.
resolve(true);
}
http.get(path)
// Call map on the response observable to get the parsed language object
.map(res => res.json())
// Subscribe to the observable to get the parsed language object and
// add its contents to the translate service.
.subscribe(translations => {
i18nHelper.langFileLoaded(path, translations);
resolve(true);
});
});
};
import {Injectable} from 'angular2/core';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {Http} from 'angular2/http';
@Injectable()
export class I18nHelper {
loadedLangFiles = [];
translate: TranslateService;
lang: string;
constructor(translate: TranslateService) {
this.translate = translate;
this.setLang(translate.currentLang);
}
langFileLoaded(fileName: string, translations?: Object) {
for (let key in translations) {
// this is really the thing:
// pushing new values into the translation map:
this.translate.set(key, translations[key], this.lang);
}
this.loadedLangFiles.push(fileName);
}
isAlreadyLoaded(fileName: string) {
return this.loadedLangFiles.indexOf(fileName) !== -1;
}
setLang(lang: string) {
this.lang = lang;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment