Search code examples
angularobservablebehaviorsubject

Cannot get and set value to BehaviorSubject in angular


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


Solution

  • 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.