垫排序工作一次然后给出错误
mat sort works one time and then gives error
我有一个动态垫 table 排序
dataSource: MatTableDataSource<MemberList>;
@Output() walkthroughData: EventEmitter<number> = new EventEmitter();
@ViewChild(MatSort, { static: true }) sort: MatSort;
data: any;
memberList: MemberList[];
membersCount: number;
ngOnInit(): void {
setTimeout(() => {
this.dataSource.sort = this.sort;
});
this.teamService.getTeamMembers().subscribe((response) => {
this.data = response['data']['result'];
this.memberList = this.data.map(({ name, role, email }) => ({
teamMember: Object.values(name).join(' '),
email,
role: role?.name,
assignedOn: [
'LA Care Health Plan',
'LA Care Health Plan',
'LA Care Health Plan',
],
}));
this.dataSource = new MatTableDataSource(this.memberList);
});
}
它只工作一次然后抛出错误
core.js:6210 ERROR TypeError: Cannot set property 'sort' of undefined
我做错了什么?
matHeaderCellDef 和 matCellDef 相同,也导入了 mat 排序模块,我也为数据源尝试了 ngAfterViewInit 但同样的错误出现
这好像是一个race-condition的问题,第一次碰巧成功了。
您的 setTimeout 在您订阅之前执行,这样,您的 dataSource 变量尚未定义。
您应该移动此代码:
this.dataSource.sort = this.sort;
在变量实例化后立即设置:
this.dataSource = new MatTableDataSource(this.memberList);
我有一个动态垫 table 排序
dataSource: MatTableDataSource<MemberList>;
@Output() walkthroughData: EventEmitter<number> = new EventEmitter();
@ViewChild(MatSort, { static: true }) sort: MatSort;
data: any;
memberList: MemberList[];
membersCount: number;
ngOnInit(): void {
setTimeout(() => {
this.dataSource.sort = this.sort;
});
this.teamService.getTeamMembers().subscribe((response) => {
this.data = response['data']['result'];
this.memberList = this.data.map(({ name, role, email }) => ({
teamMember: Object.values(name).join(' '),
email,
role: role?.name,
assignedOn: [
'LA Care Health Plan',
'LA Care Health Plan',
'LA Care Health Plan',
],
}));
this.dataSource = new MatTableDataSource(this.memberList);
});
}
它只工作一次然后抛出错误
core.js:6210 ERROR TypeError: Cannot set property 'sort' of undefined
我做错了什么? matHeaderCellDef 和 matCellDef 相同,也导入了 mat 排序模块,我也为数据源尝试了 ngAfterViewInit 但同样的错误出现
这好像是一个race-condition的问题,第一次碰巧成功了。 您的 setTimeout 在您订阅之前执行,这样,您的 dataSource 变量尚未定义。
您应该移动此代码:
this.dataSource.sort = this.sort;
在变量实例化后立即设置:
this.dataSource = new MatTableDataSource(this.memberList);