所以我的服务中有一个函数返回一个值,我希望我的组件监听该值并在它发生变化时更新它,所以我认为订阅它是个好主意,但它没有按预期工作,并且在更改时不会更新值。有没有其他方法可以做到这一点?
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);
}
我不需要知道它什么时候改变,我只需要知道它改变时要更新的值。不使用计时器,也不使用 OnLangChange 作为触发器:
ngOnInit(): void {
this.translateService.onLangChange.subscribe(() => this.localeDateAdapterService.getLocaleDateFormat().subscribe(currLang => this.currLang = currLang));
}
答案 0 :(得分:1)
使用来自 /rxjs
的主题// Service
language$ = new Subject<string>();
setLanguage(lang: string): void {
this.language$.next(lang);
}
// Component
this.language$.subscribe((res: string) => {
console.log(res);
});
this.languageSrv.setLanguage('en');
this.languageSrv.setLanguage('es');
this.languageSrv.setLanguage('it');
this.languageSrv.setLanguage('fr');
// 'en'
// 'es'
// 'it'
// 'fr'
记得退订
答案 1 :(得分:1)
我将其作为名为 LocaleService 的单独服务制作。您必须以某种方式获取当前语言,可能来自翻译服务,或者您将其作为处理它的单独服务。
Task.Wait
这去组件
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);