angulartypescriptng2-translate

ng2-translate use localstorage


I need to use localstorage to store the selected language in my Angular2 application with ng2-translate.

I found this class which is supposed to store the selected language in localstorage:

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();
                });
        });
    }
}

As it didn't work, I fixed it for my version of angular2 to this:

import {TranslateLoader} from "ng2-translate/ng2-translate";
import {Observable} from "rxjs/Observable";
import {Http, Response} from "@angular/http";
import {Injectable} from "@angular/core";

@Injectable()
export class TranslateLSLoader implements TranslateLoader {
    constructor(private http: Http) {}

    /**
     * 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(`${'i18n'}/${lang}${'.json'}`)
                .map((res: Response) => res.json())
                .subscribe((res: any) => {
                    observer.next(res);
                    localStorage.setItem('hmx-lang-' + lang, JSON.stringify(res));
                    observer.complete();
                });
        });
    }
}

Now I get no errors but it doesn't work, when I reload the page, it selects the defaut language.

Also I had to configure the ng2-translate module in my imports:

TranslateModule.forRoot({
    provide: TranslateLoader,
    useClass: TranslateLSLoader
})

Do you know what is wrong with the code?


Solution

  • A late answer but I came to your question to find out how to implement it using local storage but found no one helped you out. Somehow I am able to find out how to sort it out.
    First create Translate service object and set languages into it:

    this.translate.addLangs(['en','hn','hu']);  
    

    Make sure the language you want to use should be available in above set of added languages.

    Change TranslateLSLoader as below

    export class TranslateLSLoader implements TranslateLoader {
        constructor(private http: Http) {}
    
        public getTranslation(lang: string): Observable<any> {
            return Observable.create(observer => {
                let translations = localStorage.getItem(lang);
                if(translations) {
                    observer.next(JSON.parse(translations));
                }
            });
        }
    }  
    

    before calling TranslateLSLoader to fetch data from localStorage you need to first store data into localStorage as below

    localStorage.setItem(languageCode, lang_json);  
    

    Now call getTranslation from TranslateLSLoader

    this.translateLSLoader.getTranslation(languageCode).subscribe(data => this.translationData(data, languageCode), error => console.log(error));   
    
    translationData(data:any, languageCode:any){
                //set current translation
                this.translate.setTranslation(languageCode,data,false);
                this.translate.use(languageCode);
    }  
    

    It worked for me, let me know if you have any issues.