首页 > 解决方案 > 订阅 Angular 9 组件上可观察到的变化的适当位置

问题描述

我是 Angular 9 的新手...我的模板(主题 $)中有一个 observable,它正在正确更新,并且基于这个 observable 的值,我想通过 javascript 在我的组件定义中进行更改:

<div [class]="'headerWrapper ' + (theme$ | async)">

theme$ 是一个可观察的。

我不确定在我的组件中检查此值(即订阅 $theme)更新的正确位置是什么,而不是依赖于模板中的更新值。我试过ngOnChanges了,但这仅适用于 @Input 道具。我想在我的组件类中编写一个方法,该方法将在每次 $theme 更改时执行(不仅仅是 ngOnInit)。

我的组件:

ngOnInit() {
console.log(this, "THE THIS")
this.theme$ = this.dataService.currentTheme;}

我的服务具有可观察性:

    import { BehaviorSubject } from 'rxjs';
    public themeSource = new BehaviorSubject('dark');
    currentTheme = this.themeSource.asObservable();
      
    toggleTheme(theme) {
      this.themeSource.next(theme)
    }

标签: angularrxjsobservableangular9

解决方案


每当调用 .next() 时,行为主体都会发出一个新值。

您可以service_name.currentTheme在 ngOnInit 或 ngAfterViewInit 生命周期钩子中订阅组件中的 ,并且只要有新的发射,观察者就会收到通知。

此外,我们创建一个新变量,就像currentTheme = this.themeSource.asObservable();您的情况一样,只是为了确保行为主题themeSource对服务类保持私有,并且不会在类外访问。

所以,请将 themeSource 变量设为私有,例如 :: private themeSource = new BehaviorSubject('dark');

希望这能回答你的问题。如果您有任何疑问,请添加评论


推荐阅读