3 回答
TA贡献1860条经验 获得超9个赞
BehaviorSubject在这种情况下,您将不得不使用。BehaviorSubject不断收听订阅者并在next发出时更新。
dataSource: BehaviorSubject<MatTableDataSource[]> = new BehaviorSubject([]);
onDelete(selectedUser) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(result => {
if (result.value) {
this.userService.delete(selectedUser.id).subscribe(res => {
this.dataSource.value.data.splice(selectedUser.id, 1);
this.dataSource.next(this.dataSource.value);
});
Swal.fire('Deleted!', 'User has been deleted.', 'success');
}
});
}
其中 MatTableDataSource 应该是您的数据类型。
TA贡献1864条经验 获得超6个赞
要刷新材料数据表,最简单的方法是刷新整个数据源:
dataSource = new MatTableDataSource();
displayedColumns = ['first_name', 'middle_name', 'last_name', 'mail', 'role', 'action'];
action: any;
selectedUser: User;
@Input() user: User;
data: any;
@ViewChild(MatSort, {static: true}) sort: MatSort;
@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
constructor(private formBuilder: FormBuilder, private userService: UserService, public dialog: MatDialog) {
}
ngOnInit() {
this.loadDataTable();
}
loadDataTable() {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
this.userService.getUsers()
.subscribe(
(response) => {
this.dataSource.data = response;
},
(error) => {
console.log('error ' + error);
}
);
}
onDelete(selectedUser){
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
this.userService.delete(selectedUser.id).subscribe(res => {
this.loadDataTable();
Swal.fire(
'Deleted!',
'User has been deleted.',
'success'
);
},
// Probably you want to add some error handling here:
(error) => {
console.error(error);
});
}
})
TA贡献1833条经验 获得超4个赞
使用get 调用管道删除调用。
deleteUser(){ // called on click of delete
this.userSvc
.deleteUser() // service function that deletes a user. Could be any of CUD (Create, Update or Delete
.pipe(
switchMap(data => this.userSvc.getUsers()) // pipe the result and perform retrieve.
)
.subscribe( result => this.users = result); // finally set the result on a field to show on the component template.
}
这是一个快速示例https://stackblitz.com/edit/angular-agpxba?embed=1&file=src/app/app.component.ts
还有其他方法可以实现相同的目标,尤其是当我们使用 ngrx 等应用程序状态管理框架时。我们可能会识别状态更改并触发检索 API。这里的一个很简单。样品在 15 分钟内快速编码。
添加回答
举报