Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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