我知道,如果我想向数组BehaviorSubject 添加一个项目,我需要使用
next()
分配整个数组的副本以及新项目。
但是,我想将项目推送到这个数组中,而不必分配整个副本,我还必须在这个数组中执行其他操作,使用BehaviorSubject似乎很复杂。
有没有办法实现我想要的,或者BehaviorSubject的替代方案可以帮助我?无论是否有替代方案,是否有一个好的库可以帮助解决这个问题?
示例:
export class ArrayService {
currentArray = new BehaviorSubject<[]>([]);
addItem(){
let newItem = 'newItem';
currentArray.next([...this.currentArray.getValue(), newItem]);
}
}
创建另一个数组,推入它,然后触发它。
export class ArrayService {
currentArray = [];
currentArray$ = new BehaviorSubject<[]>(this.currentArray);
addItem(){
let newItem = 'newItem';
currentArray.push(newItem);
currentArray$.next(this.currentArray);
}
}