RxJs:递增地将数据流推送到BehaviorSubject <[]>

use*_*446 12 rxjs5 angular

基本上我正在尝试BehaviorSubject<[]>使用将以块的形式加载的数据数组进行充气.

BehaviorSubject<[]>将添加新的数据块(如Array.push),但我不想使用另一个数组来存储和添加,BehaviorSubject.next因为这将导致渲染花费太长时间随着数据的增长而增长.

有什么建议吗?

Sup*_*miu 19

您可以使用getValue()方法来实现您想要做的事情.

例:

data = new BehaviorSubject<any[]>([]);

addData(foo:any):void{
  // I'm using concat here to avoid using an intermediate array (push doesn't return the result array, concat does).
  this.data.next(this.data.getValue().concat([foo]));
}
Run Code Online (Sandbox Code Playgroud)

  • `getValue()` 让我很开心。谢谢。 (2认同)

The*_*nna 7

除了使用之外concat,您还可以使用传播运算符:

data = new BehaviorSubject<any[]>([]);

addData(foo: any): void {
  this.data.next([...this.data.getValue(), ...foo])
}
Run Code Online (Sandbox Code Playgroud)

我发现这比简单的方法更具可读性 concat