ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.51k stars 575 forks source link

ngx-translate does not retain translation on page refresh. #1097

Open prawn9189 opened 5 years ago

prawn9189 commented 5 years ago

Ok so I love this library and everything about it. However as i was fiddling around with my app, i realized that say i set my default language as English, and change it to Japanese on the home page, all other pages get changed to Japanese as well. However once i refresh the page, the translations do not retain as Japanese but instead change back to English. Are there any ways to work around this?

longgt commented 5 years ago

@prawn9189 you need to save current language to storage such as localStorage or cookie, then get it back after page refresh.

prawn9189 commented 5 years ago

@longgt but isn't that not a safe way to store it though? Currently i'm storing it in my localStorage, but i feel like it isn't the best option.

kartheininger commented 5 years ago

You need to somehow persist your state. When doing a page refresh your application is loaded from scratch. If you want to persist data between such a new load of your application (the same applies when closing your app and opening it again) you somehow need to persist your relevant data. No matter if that is done somewhere with a backend and a real database or with the available storage options of the browser. Depending on your usecase it is enough to save it in the browser, perhaps it is a setting for that user which needs to be available on multiple devices (no matter on which client he is opening your app he wants his saved language used everywhere if being logged in).

tulasi1356 commented 3 years ago

when I am using ngx translate working fine from homepage to others but if I am refreshing in the middle of any page and i am trying change the language to other it is not working correctly when i am going back and return to that page than only it is working

sarvosmi commented 2 years ago

same issue for me too

when I am using ngx translate working fine from homepage to others but if I am refreshing in the middle of any page and i am trying change the language to other it is not working correctly when i am going back and return to that page than only it is working

vokic commented 1 year ago

Nothing new on this?

clementfellah commented 9 months ago

Nothing new on this ? I have the same issue

bilelz commented 9 months ago

My code (with localStorage) when the app loads

translate.addLangs(['en', 'fr']);
translate.setDefaultLang('en');

const browserLang = translate.getBrowserLang();
const storedLang = localStorage.getItem('lang');

const lang = translate.getLangs().includes(storedLang)
  ? storedLang
  : translate.getLangs().includes(browserLang)
  ? browserLang
  : translate.defaultLang;

translate.use(lang);