问题描述
我正在尝试将一个布尔值添加到BehaviorSubject.但是,当我尝试控制台日志时,它说它是未定义的.我在做什么错了?
I'm trying to add a boolean value to a BehaviorSubject. However, when I try to console log it says that it is undefined. What I'm doing wrong?
这就是我的声明方式.
isDesktopWidth: BehaviorSubject<boolean>;
这就是我的用法
changeSideBarWidth() {
if (this.innerWidth > 767) {
this.isDesktopWidth.next(true);
} else {
this.isDesktopWidth.next(false);
}
}
然后在ngOnInit
And then in the ngOnInit
this.changeSideBarWidth();
console.log(this.isDesktopWidth.value);
但是它不会在控制台中显示任何内容.唯一的错误是
But it doesn't display anything in the console. Only an error saying that
推荐答案
您已分配了变量 isDesktopWidth
的类型,但尚未初始化它.试试
You have assigned the type of the variable isDesktopWidth
but have not initialized it. Try
isDesktopWidth = new BehaviorSubject<boolean>(false);
BehaviorSubject
需要使用一个值进行初始化.如果要创建没有初始化程序的对象,请使用 Subject
.在这种情况下,您可以使用
BehaviorSubject
needs to be initialized with a value. If you wish to create without an initializer, use Subject
. In that case you could use
isDesktopWidth = new Subject<boolean>();
它们之间的另一个区别是 BehaviorSubject
拥有一个值.因此,一旦您订阅它,它将返回它持有的当前值. Subject
不保存当前值.当您订阅它时,您将不会收到一个值,直到它发出下一个值为止.
Another difference between them is BehaviorSubject
holds a value. So it will return the current value it holds as soon you subscribe to it. Subject
does not hold the current value. When you subscribe to it, you will not receive a value till it emits the next one.
在未发布的主题
上使用 .value
属性将返回 undefined
.
Using .value
property on a unemitted Subject
will return undefined
.
这篇关于无法获取和设置值到BehaviorSubject以角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!