首页 > 解决方案 > 在 Angular 7 中刷新 datatables.net 表数据会保留表第一次加载时的旧数据副本

问题描述

我正在尝试使用 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>

标签: angulardatatablesangular7angular-datatables

解决方案


您必须先销毁表并重新渲染。你可以参考这里的文章。如果链接将来被禁用,则为代码片段。

rerender(): void {
this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
  // Destroy the table first
  dtInstance.destroy();
  // Call the dtTrigger to rerender again
  this.dtTrigger.next();
});
}

另一种解决方案是讨论here

让我知道此解决方案是否有效或您有任何疑问。


推荐阅读