首页 > 解决方案 > 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()不会改变结果。谢谢!:)

标签: javascripthtmlangulartypescriptbehaviorsubject

解决方案


在您的服务中,您可以像这样创建和公开 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
  });

推荐阅读