Angular4 Material数据表格如何实现无页面刷新更新数据?
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
BehaviorSubjectinUserDataSourcekeeps track of the current user list. When you callnext()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
createdUserobject from your API matches the structure of yourUsermodel (so all columns indisplayedColumnshave the correct data). - If your API doesn't return the full user object, you can use the
submittedDatainstead (just make sure it has all the fields your table needs).
内容的提问来源于stack exchange,提问作者Manav

