无法获取和设置值到BehaviorSubject以角度 [英] Cannot get and set value to BehaviorSubject in angular

查看:58
本文介绍了无法获取和设置值到BehaviorSubject以角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个布尔值添加到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

无法读取未定义的属性"next"

Cannot read property 'next' of undefined

推荐答案

您已分配了变量 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以角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆