我正在尝试使用Angular 7中的datatables.net库从REST API请求进行实时报告。如果我将数据更新到数据库中,则表中的数据会更新。但是,如果我触摸表(即重新排序,搜索某些内容,更改页面等),则在数据重新加载(每5秒发生一次)时,在表中添加来自表的第一次加载的数据。如果我再次触摸表格,更新的数据将消失,只有旧数据保留,直到下一次数据更新,再次在表格中添加新数据。
这是更新数据库中数据时表的状态
当对表进行任何更改时(即排序,搜索,切换页面等),这是表的行为
这是组件的代码:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { DownloadService } from '../services/download/download.service';
import { stringify } from 'querystring';
import { Router } from '@angular/router';
@Component({
selector: 'app-downloads',
templateUrl: './downloads.component.html',
styleUrls: ['./downloads.component.css']
})
export class DownloadsComponent implements OnInit {
downloadData$: any[] = [];
dtOptions: DataTables.Settings = {};
dtTrigger: Subject<any> = new Subject();
interval: any;
constructor(private http: HttpClient, private data: DownloadService, private router: Router) { }
ngOnInit() {
this.dtOptions = {
responsive: true
};
this.data.GetDownloads().subscribe(data => {
this.downloadData$ = data;
this.dtTrigger.next();
});
this.interval = setInterval(() => {
this.refreshData();
}, 5000);
}
refreshData() {
this.data.GetDownloads().subscribe(data => {
this.downloadData$ = data;
});
}
ngOnDestroy(): void {
this.dtTrigger.unsubscribe();
}
}
这是html文件
<div>
<table style="text-align: center;" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%"
datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger">
<thead>
<tr>
<th>Logger Name</th>
<th>Progress</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let download of downloadData$">
<td>{{ download.logger.name }}</td>
<td [attr.data-order]="download.progress"><progress [attr.value]="download.progress" max="100"></progress>
{{ download.progress }}%</td>
</tr>
</tbody>
</table>
</div>
我试了一下,这种行为非常奇怪,它默认回到原始值。这不是您的代码的问题,而是使用angular-datatable库。
同时降级到[email protected]使用
npm install --save [email protected]
或yarn add [email protected]
我尝试了它,它工作正常。