angular - 订阅 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)
}
解决方案
每当调用 .next() 时,行为主体都会发出一个新值。
您可以service_name.currentTheme
在 ngOnInit 或 ngAfterViewInit 生命周期钩子中订阅组件中的 ,并且只要有新的发射,观察者就会收到通知。
此外,我们创建一个新变量,就像currentTheme = this.themeSource.asObservable();
您的情况一样,只是为了确保行为主题themeSource
对服务类保持私有,并且不会在类外访问。
所以,请将 themeSource 变量设为私有,例如 ::
private themeSource = new BehaviorSubject('dark');
希望这能回答你的问题。如果您有任何疑问,请添加评论
推荐阅读
- c++ - malloc 在 C++17 中是否返回“无效指针值”?
- javascript - 如何使用电子的相对路径从 html 显示本地图像?
- javascript - 将 promise 组合成 promise.all
- reactjs - React hooks:我在做一个反模式吗?更新组件外函数中的状态
- azure - 在两个区域上启用读取和写入的 AZURE COSMOS DB,我们可以在两个区域上运行 ADF 管道吗?
- r - `sheets_auth`(来自 `googlesheets4`)不适用于使用 `googleAuthR` 包创建的令牌
- php - 在php中将数组转换为xml
- excel - 使用Word文档中的句子引用提取页码
- node.js - 如何将 node_modules 文件夹添加到现有的角度文件?
- ios - 如何使用 Flutter 在 iOS 中测试验证 InAppPurchase