Angular Material 2: How to refresh md-table after editing a record?

喜欢而已 提交于 2019-12-07 12:12:45

问题


So I have a user-list component and a user-detail component.

The user-list component has an md-table listing all users registered. The user is able to click on a button to see the details of the corresponding entity.

After editing the Name property and saving (for example), the user-detail redirects to the user-list component. But the md-table displays the old information.

How can I trigger an md-table refresh after editing the entity in another component like this scenario?

Here is my user-list component:

export class UserListComponent implements OnInit {
tableDisplayedColumns: string[] = ['userName', 'email', 'options'];
userDataSource: UserDataSource;

constructor(private _userService: UserService, private _router: Router) { }

ngOnInit(): void {
    this.userDataSource = new UserDataSource(this._userService);
}}



class UserDataSource extends DataSource<UserVModel> {
constructor(private _userService: UserService) { 
    super();
}

connect(): Observable<UserVModel[]> {
    return this._userService.getAllUsers();
}

disconnect(): void { }}

回答1:


The table will re-render when the stream provided by connect() emits a new value.

getAllUsers needs to emit a new set of data when it is changed. Otherwise, listen for a separate stream (e.g. dataChanged) from the _userService and use that to call getAllUsers again.

connect(): Observable<UserVModel[]> {
  return this._userService.dataChanged
      .switchMap(() => this._userService.getAllUsers()
}



回答2:


Actually the problem was that the User-Detail component was redirecting before the observable had the chance to complete. So I placed the router.navigate as a complete function.

Code Before

onSubmit() {
    this._updateSub = this._service.updateUser(this._id, this._userForm.value)
                                        .subscribe(null, err => this.onSubmitError(err));
    this._router.navigate(['/user']);
}

Code After

onSubmit() {
    this._updateSub = this._service.updateUser(this._id, this._userForm.value)
                                        .subscribe(null, err => this.onSubmitError(err), () => this.afterSubmit());
}
afterSubmit() {
    this._router.navigate(['/user']);
}

Prior to this change, I was getting the old values after the redirect. Using the complete function, I get up to date values without the need to use a dataChanged observable in the service.




回答3:


You could tidy things up and put your router navigation inside the response :

onSubmit() {
this._updateSub = this._service.updateUser(this._id, 
this._userForm.value).subscribe(
   res => this._router.navigate(['/user']);
   err => this.onSubmitError(err), () => this.afterSubmit());
}


来源:https://stackoverflow.com/questions/45288271/angular-material-2-how-to-refresh-md-table-after-editing-a-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!