如何订阅经过过滤的Observable?设置用户失效后列表未正确过滤
问题原因
RxJS 的 BehaviorSubject 不会自动检测引用类型(数组、对象)内部的属性变化,只有手动调用next()方法推送新值时,订阅者才会收到更新触发后续逻辑执行。你在setToInactive方法中仅修改了数组内用户对象的isActive属性,没有向userList$推送更新后的数组,导致userList$始终停留在初始发射的数组值,过滤逻辑不会重新执行,模板自然也不会更新。
修复方案
1. 修改UserService的setToInactive方法
修改完用户状态后主动推送新的数组到userList$,推荐采用不可变更新的方式避免引用残留引发的意外副作用:
setToInactive(user: user) { const targetIndex = this.userList.findIndex(item => item === user); if (targetIndex === -1) return; // 不可变更新数组,生成全新的数组实例,避免原引用被意外修改 this.userList = this.userList.map((item, index) => index === targetIndex ? {...item, isActive: false} : item ); // 手动推送更新后的数组 this.userList$.next(this.userList); }
如果不需要严格的不可变更新,也可以采用简化写法:
setToInactive(user: user) { const currentUser = this.userList.find(x => x == user); if(currentUser != undefined) { currentUser.isActive = false; // 解构生成新数组推送即可触发更新 this.userList$.next([...this.userList]); } }
2. 可选优化:简化过滤逻辑
isActive本身就是布尔值,不需要额外和true做等值判断,同时修改参数名增强可读性:
getActiveUsers(): Observable<user[]> { return this.userList$.asObservable().pipe( map(userList => userList.filter(x => x.isActive)) ); }
修改完成后点击按钮修改用户状态时,userList$会发射新的数组值,过滤逻辑会自动执行,模板也会同步更新仅展示活跃用户。
内容的提问来源于stack exchange,提问作者Chen Long
相关产品推荐
相关产品推荐

