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

Luc*_*mnt 4 behaviorsubject angular

这是我的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); }
    });
}
Run Code Online (Sandbox Code Playgroud)

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[]>'.
Run Code Online (Sandbox Code Playgroud)

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

谢谢

pre*_*fly 8

如果您正在使用a,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);
}
Run Code Online (Sandbox Code Playgroud)