Search code examples
angularrxjsionic4

How can I assign a number to a type 'BehaviorSubject<number>'


How to assign a number to type 'BehaviorSubject<number>'?


Solution

  • Here is the example.

    you can create BehaviourSubject like below.

    counter$ = new BehaviorSubject<number>(1);
    
      onIncreaseCounter() {
        let counterVal = this.counter$.value;
        this.counter$.next(counterVal + 1);
      }
    

    then you can use it like below.

    <h2>Counter</h2>
    <div>{{ counter$ | async }}</div>
    
    <button (click)="onIncreaseCounter()">Increase Counter</button>
    

    check working demo