You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular4 Material数据表格如何实现无页面刷新更新数据?

How to Update Angular Material Table Without Page Refresh After Adding New Data

Got it, let's get your Angular Material table to show the new user right away without needing a page refresh! Here's a straightforward approach tailored to your setup:

Step 1: Adjust Your UserDataSource to Support Dynamic Updates

First, your custom DataSource needs a way to emit new data when a user is added. Using a BehaviorSubject is perfect here because it holds the current data state and emits updates to subscribers (like your table).

Update your UserDataSource class like this:

import { DataSource } from '@angular/cdk/collections';
import { BehaviorSubject, Observable } from 'rxjs';
import { User } from './your-user.model'; // Import your User model
import { UserService } from './your-user.service';

export class UserDataSource extends DataSource<User> {
  // BehaviorSubject to hold and emit the current list of users
  private usersSubject = new BehaviorSubject<User[]>([]);

  constructor(private userService: UserService) {
    super();
  }

  // Load initial users from the service
  loadUsers() {
    this.userService.getUsers().subscribe(users => {
      this.usersSubject.next(users);
    });
  }

  // Connect the data source to the table
  connect(): Observable<User[]> {
    return this.usersSubject.asObservable();
  }

  disconnect(): void {
    this.usersSubject.complete();
  }

  // Method to add a new user to the existing list
  addNewUser(newUser: User) {
    // Get current users, create a new array with the new user added
    const updatedUsers = [...this.usersSubject.value, newUser];
    // Emit the updated array to trigger table refresh
    this.usersSubject.next(updatedUsers);
  }
}

Step 2: Update Your Component to Trigger the Table Refresh

In your component where you handle the dialog close and API call, call the addNewUser method on your dataSource once the API successfully creates the user.

Modify your existing code like this:

dialogRef.afterClosed().subscribe(submittedData => {
  // Only proceed if the user submitted data (not canceled the dialog)
  if (submittedData) {
    this.userService.makeRegister(token, submittedData).subscribe(
      (createdUser) => {
        console.log('User registered successfully:', createdUser);
        // Add the newly created user to the table
        this.dataSource.addNewUser(createdUser);
      },
      (error) => {
        // Don't forget to handle API errors!
        console.error('Failed to register user:', error);
      }
    );
  }
});

Step 3: Ensure Initial Data Load (If Needed)

Make sure you load the initial users when your component initializes. Add this to your component's ngOnInit method:

ngOnInit() {
  this.dataSource.loadUsers();
}

Why This Works

  • The BehaviorSubject in UserDataSource keeps track of the current user list. When you call next() with the updated array, it emits the new data to the table.
  • The Angular Material table subscribes to the observable returned by connect(), so it automatically updates its view whenever new data is emitted—no page refresh required!

Quick Notes

  • Ensure the createdUser object from your API matches the structure of your User model (so all columns in displayedColumns have the correct data).
  • If your API doesn't return the full user object, you can use the submittedData instead (just make sure it has all the fields your table needs).

内容的提问来源于stack exchange,提问作者Manav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:59:45