在 angular 9 组件上订阅可观察变化的适当位置

proper place to subscribe to observable changing on angular 9 component

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

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

theme$ 是一个可观察对象。

我不确定在我的组件中检查这个值(即订阅 $theme)更新的正确位置是什么,而不是依赖于它在模板中的更新值。我尝试了 ngOnChanges 但这仅适用于 @Input 道具。我想在我的组件 class 中编写一个方法,它会在每次 $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)
    }

每当 .next() 被调用时,行为主题将发出一个新值。

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

此外,我们在您的案例中创建了一个新变量,如 currentTheme = this.themeSource.asObservable();,只是为了确保行为主题 themeSource 对服务 class 保持私有,并且不会在 class.

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

希望这能回答您的问题。有疑问请留言