This is a little data service in my Angular5 app. I am trying to add/remove item from an array (actually a 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); }
});
}
The addRoomArr functions works, but not the removeRommArr. Error is :
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[]>'.
Somehow I have to convert my BehaviorSubject into an array so that I can use .forEach(). How can i manage to do that ?
Thanks
If you're using a BehaviourSubject
then you have access to getValue()
, so you want to splice the current value and then update the subject.
removeRoomArr(data: any) {
const roomArr: any[] = this.roomArr_source.getValue();
roomArr.forEach((item, index) => {
if (item === data) { roomArr.splice(index, 1); }
});
this.roomArr_source.next(roomArr);
}