【问题标题】:proper place to subscribe to observable changing on angular 9 component订阅 Angular 9 组件上可观察到的变化的适当位置
【发布时间】:2020-06-30 19:09:33
【问题描述】:

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

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

theme$ 是一个 observable。

我不确定在我的组件中检查此值(即订阅 $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)
    }

【问题讨论】:

    标签: angular rxjs observable angular9


    【解决方案1】:

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

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

    此外,在您的情况下,我们会创建一个新变量,例如 currentTheme = this.themeSource.asObservable();,以确保行为主体 themeSource 对服务类保持私有,并且不能在类外访问。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2018-01-19
      • 1970-01-01
      • 2018-11-26
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多