下面是一个使用计时器每5秒刷新表格的Angular代码示例:
*ngFor
循环来展示表格数据:
Name
Age
City
{{ person.name }}
{{ person.age }}
{{ person.city }}
import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit, OnDestroy {
timer: Subscription;
people: any[] = [];
ngOnInit() {
this.timer = interval(5000).subscribe(() => {
this.refreshTable();
});
}
ngOnDestroy() {
if (this.timer) {
this.timer.unsubscribe();
}
}
refreshTable() {
// 模拟异步获取表格数据
setTimeout(() => {
this.people = [
{ name: 'John', age: 30, city: 'New York' },
{ name: 'Alice', age: 25, city: 'London' },
{ name: 'Bob', age: 35, city: 'Paris' }
];
}, 1000);
}
}
在上面的代码中,首先导入了interval
和Subscription
类。在ngOnInit
生命周期钩子中,创建一个计时器并订阅每5秒触发一次的间隔流。在每次计时器触发时,调用refreshTable
方法来刷新表格数据。在refreshTable
方法中,使用setTimeout
模拟异步获取表格数据,并更新people
数组。在ngOnDestroy
生命周期钩子中,取消订阅计时器以避免内存泄漏。
这样就可以在Angular应用中使用计时器每5秒刷新表格了。