命令的好坏取决于你如何使用它。
发布
使用
next
方法。下面是它在引擎盖下的样子:
// update this._value and call Subject's next method
next(value: T): void {
super.next(this._value = value);
}
// Subject's next method
next(value?: T) {
if (this.closed) {
throw new ObjectUnsubscribedError();
}
if (!this.isStopped) {
const { observers } = this;
const len = observers.length;
const copy = observers.slice();
for (let i = 0; i < len; i++) {
copy[i].next(value);
}
}
}
如果要更新当前值并将其发送给观察者,则很难更直接。
获取当前值
从任何可观测数据中获取价值的自然方法是订阅它。
在大多数情况下,
getValue
真是个坏主意因为,
在大多数情况下,
可观测数据是链接的,异步使用例如,如果要合并或压缩两个订阅服务器的值,方法是:
zip(Subject_1, myBehaviorSubject).subscribe( val=> console.log(val));
现在,在某些情况下,您只需要同步地访问当前值,而不需要链接运算符。在这种情况下,使用
获取值
是的。引擎盖下:
getValue(): T {
if (this.hasError) {
throw this.thrownError;
} else if (this.closed) {
throw new ObjectUnsubscribedError();
} else {
return this._value;
}
}