Cannot get and set value to BehaviorSubject in angular

杀马特。学长 韩版系。学妹 提交于 2021-02-08 11:51:26

问题


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?

This is how I declare it.

isDesktopWidth: BehaviorSubject<boolean>;

And this is how I use it

changeSideBarWidth() {
if (this.innerWidth > 767) {
  this.isDesktopWidth.next(true);
} else {
  this.isDesktopWidth.next(false);
}

}

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

Cannot read property 'next' of undefined


回答1:


You have assigned the type of the variable isDesktopWidth but have not initialized it. Try

isDesktopWidth = new BehaviorSubject<boolean>(false);

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>();

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.

Using .value property on a unemitted Subject will return undefined.



来源:https://stackoverflow.com/questions/60773773/cannot-get-and-set-value-to-behaviorsubject-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!