Skip to content

Instantly share code, notes, and snippets.

@ocombe
Created April 27, 2016 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ocombe/7264180b5e8eff90641063840b53f4f3 to your computer and use it in GitHub Desktop.
Save ocombe/7264180b5e8eff90641063840b53f4f3 to your computer and use it in GitHub Desktop.
ng2-translate file loader with localstorage to speed up things
import {TranslateLoader} from "ng2-translate/ng2-translate";
import {Observable} from "rxjs/Observable";
import {Response, Http} from "angular2/http";
export class TranslateLSLoader implements TranslateLoader {
constructor(private http: Http, private prefix: string = 'i18n', private suffix: string = '.json') {}
/**
* Gets the translations from the localStorage and update them with the ones from the server
* @param lang
* @returns {any}
*/
public getTranslation(lang: string): Observable<any> {
return Observable.create(observer => {
let translations = localStorage.getItem('ng2-translate-' + lang);
if(translations) {
observer.next(JSON.parse(translations));
}
this.http.get(`${this.prefix}/${lang}${this.suffix}`)
.map((res: Response) => res.json())
.subscribe((res: any) => {
observer.next(res);
localStorage.setItem('hmx-lang-' + lang, JSON.stringify(res));
observer.complete();
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment