Search code examples
angularservicecomponents

Angular listen to function that returns some variable


So I have a function in my service that's returning a value and I want my component to be listening to the value and update it when it changes so I thought It would be a good idea to subscribe to it but it doesn't work as intended and doesn't update the value when it changes. Is there a different way to do this?

 ngOnInit(): void {
    this.translateService.onLangChange.subscribe(() => this.getLocaleDateFormat());
  }

 getLocaleDateFormat(): Observable<string> {
   this.dateAdapter.setLocale(Languages[this.translateService.currentLang]);
   this.currLang = Languages[this.translateService.currentLang];
    console.log( 'get' + this.currLang);
    return of (this.currLang);

  }

ngOnInit(): void {
    this.localeDateAdapterService.getLocaleDateFormat().subscribe(currLang => this.currLang = currLang);
}

I don't need to know when it changes I just the value to update when it changes. Without using a timer and also without using OnLangChange as a trigger:

ngOnInit(): void {
 this.translateService.onLangChange.subscribe(() => this.localeDateAdapterService.getLocaleDateFormat().subscribe(currLang => this.currLang = currLang));
}

Solution

  • I made it as as a separate service called LocaleService. You somehow have to get the current language maybe from translate service or if you make it as a separate service that handles it.

    private onLanguageChange(lang: string): void {
            // To add another lang:
            // 1. add mapping from EMS language codes to Angular locale codes in the map at the bottom of this file
            // 2. register locale data, also at the bottom of this file
            const locale = Languages[lang];
            this.activeLocale.next(locale);
            this.dateAdapter.setLocale(locale);
            this.LW.log('Language change detected (current lang: ' + lang + '), setting locale to: ' + locale);
          }
        
          public getActiveLocale(): BehaviorSubject<string> {
            return this.activeLocale;
          }
        export const Languages = {
          'eng': 'en',
          'slk': 'sk',
          'cze': 'cs',
        };
        
        registerLocaleData(localeSk);
        registerLocaleData(localeCs);
    

    this goes to the Component

    this.localeService.getActiveLocale().subscribe(locale => this.currentLocale = locale));