Angular:从BehaviorSubject <any []>([])中删除项目

时间:2018-03-08 15:15:00

标签: angular behaviorsubject

这是我的Angular5应用程序中的一个小数据服务。 我正在尝试从数组中添加/删除项目(实际上是一个BehaviorSubject)。

data.service.ts

private roomArr_source = new BehaviorSubject<any[]>([]);
current_roomArr = this.roomArr_source.asObservable();

addRoomArr(data: any) {
    this.roomArr_source.next(this.roomArr_source.getValue().concat([data]));
}

removeRoomArr(data: any) {
    this.roomArr_source.forEach((item, index) => {
        if(item === data) { this.roomArr_source.splice(index, 1); }
    });
}

addRoomArr函数可以工作,但不能使用removeRommArr。 错误是:

error TS2345: Argument of type '(item: any, index: any) => void' is not assignable to parameter of type '(value: any[]) => void'.
error TS2339: Property 'splice' does not exist on type 'BehaviorSubject<any[]>'.

不知何故,我必须将BehaviorSubject转换为数组,以便我可以使用.forEach()。 我怎么能设法做到这一点?

由于

1 个答案:

答案 0 :(得分:6)

如果您使用BehaviourSubject,则可以访问getValue(),因此您希望拼接当前值,然后更新主题。

removeRoomArr(data: any) {
    let roomArr: any[] = this.roomArr_source.getValue();
    roomArr.forEach((item, index) => {
        if(item === data) { roomArr.splice(index, 1); }
    });
    this.roomArr_source.next(roomArr);
}