【问题标题】:Angular : remove item from BehaviorSubject<any[]>([])Angular:从 BehaviorSubject<any[]>([]) 中删除项目
【发布时间】:2018-03-08 15:15:00
【问题描述】:

这是我的 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()。 我怎样才能做到这一点?

谢谢

【问题讨论】:

  • 数据是什么样的?请read this
  • @MikeTung data 是一个简单的字符串;感谢分享

标签: angular behaviorsubject


【解决方案1】:

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

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);
}

【讨论】:

  • 使用this.roomArr_source.getValue().splice(index, 1) 后,源数据已通过引用更改,因此您似乎不需要调用next
  • 如果这是不好的做法,您可以使用 let roomArr: any[] = [...this.roomArr_source.getValue()] 复制源代码,然后使用 this.roomArr_source.next(roomArr)
  • 这对我不起作用——next() 不会更新 BehaviorSubject (Angular 8+)。我怀疑是因为它与下一个值发送的数组相同,因此未被检测为更改。一个快速的解决方法是克隆数组this.roomArr_source.getValue().slice()
猜你喜欢
  • 2021-04-03
  • 2019-01-19
  • 1970-01-01
  • 2017-06-10
  • 2018-01-18
  • 2021-10-23
  • 2020-04-17
  • 1970-01-01
  • 2021-11-01
相关资源
最近更新 更多