我有一个用户列表,它在ngOnInit()上被初始化,当我删除、添加或修改一个用户时,HTML组件用reloadData()函数重新渲染就好了...但是当我从我的webskoket服务上收到一个消息,我调用reloadData()函数时,它从数据库中刷新了模型,但没有刷新视图。
这是我的EmployeesComponent.ts的reloadData()函数。
private reloadData() {
this.users = [];
console.log('reloading employees..');
console.log(this.users);
this.userService.list().subscribe(r => {
if (this.router.url === '/RemoteMonitoring/(mainCon:Departments)' && this.clickedDep.depId !== -1) {
this.chefDep = null;
this.setChefDep(this.clickedDep.depId);
this.usersForDep = r;
for (const emp of this.usersForDep) {
if (emp.department.depId === this.clickedDep.depId) {
this.users.push(emp);
}
}
this.clickedDep.users = [];
this.clickedDep.users = this.users;
this.outPutData.emit();
} else {
this.userService.findUserWithToken().subscribe(us => {
for (const emp of r) {
// @ts-ignore
if (emp.userId !== us.userId) {
this.users.push(emp);
}
}
});
}
});}
这是我显示 users[] 的地方
<tr *ngFor="let emp of users; let i = index; trackBy:identify">...</tr>
这是在*ngFor中调用的标识函数。
identify(index, item) {
return index;
}
这是由websocket触发的函数,在它里面我调用了reloadData()。
reloadFromSocket() {
console.log('Reloading users from websocket...');
this.reloadData();
}
我知道代码工作得很好,因为我在控制台记录了所有的东西......而且你可以看到这里的 "从websocket重新加载用户..." 消息被记录下来...控制台屏幕截图
模型正在重新加载,但视图没有重新渲染。
谢谢😁。
我发现了问题所在...我将组件注入到服务中,因此它创建了一个新的实例...所以它重载了新实例的数据,但没有渲染到屏幕上的数据,这就是解决这个问题的方法。