0

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

Csibi Norbert
  • 780
  • 1
  • 11
  • 35

1 Answers1

3

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.

ruth
  • 29,535
  • 4
  • 30
  • 57
  • Thanks @MichaelD, I have another problem which doesn't change the value at all...It is always true, why is this happening? – Csibi Norbert Mar 20 '20 at 12:37
  • Based on your condition, I'd assume `this.innerWidth` variable might always be greater than 767. – ruth Mar 20 '20 at 12:38
  • Actually is not, if I will console log the innerWidth, it changes the screen size number. And when it is below 767 it consoles log whatever I put in that else statement. – Csibi Norbert Mar 20 '20 at 12:50
  • 1
    Then try subscribing to it. In `ngOnInit()`, do `this.isDesktopWidth.subscribe(r => { console.log(r); });` – ruth Mar 20 '20 at 13:00