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

Time:12-28

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

CodePudding user response:

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

CodePudding user response:

You can specify a number in the parameter of BevahiourSubject:

public yourVariable = new BehaviorSubject<number>(1);

In your subscription, you can assign number any time like:

yourVariable.next(2);
  • Related