LanguageService.ts 949 B

12345678910111213141516171819202122232425262728293031323334353637
  1. export class LanguageService {
  2. private listeners: Array<() => void> = [];
  3. private document: Document = document;
  4. constructor (private lsKey: string, private defaultLang = 'pt') {
  5. this.setupListener();
  6. }
  7. setupListener (): void {
  8. if(this.document !== null) {
  9. this.document.addEventListener("storage",(event => {
  10. const e = event as StorageEvent;
  11. if(e.key === this.lsKey) {
  12. this.listeners.forEach(l => l());
  13. }
  14. }));
  15. }
  16. }
  17. getLang (): string {
  18. const lang = localStorage.getItem(this.lsKey);
  19. if(lang === null || lang === undefined) {
  20. console.warn("Internal Error: User language information has not been set. Returning default...");
  21. return this.getDefaultLang();
  22. }
  23. return lang;
  24. }
  25. getDefaultLang (): string {
  26. return this.defaultLang;
  27. }
  28. registerLanguageChangeListener (listener: () => void) {
  29. this.listeners.push(listener);
  30. }
  31. }