在Angular 7中刷新datatables.net表数据会保留表的第一次加载时旧数据的副本

问题描述 投票:1回答:2

我正在尝试使用Angular 7中的datatables.net库从REST API请求进行实时报告。如果我将数据更新到数据库中,则表中的数据会更新。但是,如果我触摸表(即重新排序,搜索某些内容,更改页面等),则在数据重新加载(每5秒发生一次)时,在表中添加来自表的第一次加载的数据。如果我再次触摸表格,更新的数据将消失,只有旧数据保留,直到下一次数据更新,再次在表格中添加新数据。

这是页面加载State of the table on page load时表的状态

这是更新数据库中数据时表的状态

state of the table when the data in the database is updated

当对表进行任何更改时(即排序,搜索,切换页面等),这是表的行为behavior of the table when any change is made on the table

这是组件的代码:

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 datatables angular7 angular-datatables
2个回答
1
投票

你必须先破坏表并重新渲染。你可以参考文章here。如果链接将来被禁用,则为代码段。

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

如果此解决方案有效或者您有任何疑问,请告诉我。


0
投票

我试了一下,这种行为非常奇怪,它默认回到原始值。这不是您的代码的问题,而是使用angular-datatable库。

同时降级到[email protected]使用

npm install --save [email protected]yarn add [email protected]

我尝试了它,它工作正常。

© www.soinside.com 2019 - 2024. All rights reserved.