【问题标题】:How can I assign a number to a type 'BehaviorSubject<number>'如何将数字分配给类型 'BehaviorSubject<number>'
【发布时间】:2021-12-28 05:10:12
【问题描述】:

如何分配一个数字来键入'BehaviorSubject'?

【问题讨论】:

标签: angular rxjs ionic4


【解决方案1】:

可以在BevahiourSubject的参数中指定一个数字:

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

在您的订阅中,您可以随时分配号码,例如:

yourVariable.next(2);

【讨论】:

【解决方案2】:

这是一个例子。

你可以像下面这样创建BehaviourSubject

counter$ = new BehaviorSubject<number>(1);

  onIncreaseCounter() {
    let counterVal = this.counter$.value;
    this.counter$.next(counterVal + 1);
  }

那么你可以像下面这样使用它。

<h2>Counter</h2>
<div>{{ counter$ | async }}</div>

<button (click)="onIncreaseCounter()">Increase Counter</button>

检查working demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 2012-08-24
    • 2017-01-05
    • 2021-09-18
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多