javascript - Angular:BehaviorSubject 未按预期工作
问题描述
我试图在 Angular 中获取 BevhaviorSubject 的当前值。我使用以下两行将每个内容(整个内容和值)打印到控制台以检查其内容:
console.log(this._isNumeric)
console.log(this._isNumeric.getValue())
...但我收到的是:
closed: false
hasError: false
isStopped: false
observers: []
thrownError: null
_isScalar: false
_value: true
value: true
__proto__: Subject
对于主题(注意 value 参数设置为 true)和
false
如果我只是打印价值。也许我犯了一个明显的错误,但是有人知道如何获得 BehaviorSubject 的实际值吗?使用.value
而不是.getValue()
不会改变结果。谢谢!:)
解决方案
在您的服务中,您可以像这样创建和公开 BehaviorSubject:
private _isNumeric$ = new BehaviorSubject<boolean>(false); // first value is false
/** Protects the _isNumeric$ BehaviorSubject from outside access */
public get IsNumeric$(): Observable<boolean> {
return this._isNumeric$.asObservable();
}
// NOTE: This is how you can access the value within the service
private get IsNumeric(): boolean {
return this._isNumeric$.getValue();
}
澄清变量名末尾的“$”的使用。它不做任何事情,只是有时按惯例使用它来指示变量持有 Observable 或函数将返回 Observable。
如果你想发出一个新值,你可以在 BehaviorSubject 上使用 '.next()'
this._isNumeric$.next(true); // Emit a value of true
如果您想从组件访问数据,您可以通过订阅它来检索数据,就像这样。记得取消订阅 BehaviorSubject。
this.yourService.IsNumeric$
.pipe(takeUntil(this.onDestroy$)) // This is just a subject used to unsubscribe later
.subscribe((value: boolean) => {
// Use the result from the BehaviorSubject
});
推荐阅读
- powerapps - 读取 csv 文件并处理数据
- jquery - 使用jQuery克隆后如何更改名称属性?
- c++ - svm-scale:找不到命令
- c# - 扩展器扩展时扩展网格
- html - 如何在 Angular 6 中的两个组件之间共享 http 响应?
- c - MongoDB .NET Find().ToList() 操作对于大结果来说很慢
- javascript - 将数组推送到数组中包含的对象中
- ionic-framework - Ionic 2:如何制作从底部打开并在其中播放音乐的菜单
- laravel - 为什么我无法点击通知、消息、个人资料部分
- java - Java 异常处理和循环继续