Angular Material表格新增数据需刷新才显示的问题求助
Angular Material表格新增数据后不自动渲染的解决方案
问题出在StudentService的createStudent方法里:你直接修改了原数组的内容,而BehaviorSubject只有在接收到新的数组引用时才会通知订阅者更新。
具体原因
你在createStudent中用let newList = this.studentsSubject.getValue();获取了当前数组的引用,然后用newList.push(newStudent)修改这个数组——这只是改变了数组内部的元素,数组本身的引用没有变。而updateStudent和deleteStudent方法里用了map、filter,这些方法会返回全新的数组,所以能触发BehaviorSubject的通知,让组件更新数据、表格重新渲染。
修改方案
把createStudent方法改成以下两种方式之一,确保传递给studentsSubject.next()的是新数组:
方式一:创建原数组副本再添加元素
createStudent(student: Student): void { let newId = this.studentsSubject.getValue().length + 1; let newStudent = {...student, id: newId, commissionId: null}; // 用扩展运算符创建原数组的副本,而非直接引用原数组 let newList = [...this.studentsSubject.getValue()]; this.httpClient.post('https://63cc20169b72d2a88e0893c6.mockapi.io/alumnos', newStudent).subscribe(_ => { newList.push(newStudent); this.studentsSubject.next(newList); }) }
方式二:直接生成包含新元素的新数组
createStudent(student: Student): void { let newId = this.studentsSubject.getValue().length + 1; let newStudent = {...student, id: newId, commissionId: null}; this.httpClient.post('https://63cc20169b72d2a88e0893c6.mockapi.io/alumnos', newStudent).subscribe(_ => { // 直接合并原数组和新元素,生成新数组 const updatedList = [...this.studentsSubject.getValue(), newStudent]; this.studentsSubject.next(updatedList); }) }
额外建议
尽量避免用getValue()直接获取BehaviorSubject的当前值,更规范的做法是通过订阅流来处理,但当前场景下,解决数组引用的问题就能直接修复表格不更新的问题。
内容的提问来源于stack exchange,提问作者Andrés Marolt
相关产品推荐
相关产品推荐

