在 Angular 2 中重新渲染数据表 - dtInstance.then 错误

Shi*_*ral 3 datatable angular

我的 angular 2 应用程序中有一个组件,它有一个下拉列表和一个数据表。根据从下拉列表中选择的名称,我想在数据表中显示详细信息。

HTML -

<div>
  <select [(ngModel)]="selectedName">
    <option *ngFor="let name of nameList" value= {{name.firstName}} >
      {{name.firstName}}
    </option>
  </select>

  <button id="submitName" (click)="getData()">Go</button>
</div>

<table #myTable [dtTrigger]="dtTrigger" datatable class="row-border hover">
  <thead>
    <tr>
      <th>ID</th>
      <th>First name</th>
      <th>Last Name</th>
      <th>Middle Name</th>
    </tr>
  </thead>
  <tbody *ngIf="retrievedNames">


      <tr *ngFor="let name of retrievedNames">
        <td>{{name.id}}</td>
        <td>{{name.firstName}}</td>
        <td>{{name.lastName}}</td>
        <td>{{name.middleName}}</td>
      </tr>


  </tbody>

</table>
Run Code Online (Sandbox Code Playgroud)

我的组件.ts

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { NetworkService } from './../services/network.service';
import { Subject } from 'rxjs/Rx';
import { Router } from '@angular/router';
import { DataTableDirective } from 'angular-datatables';

@Component({
  selector: 'app-namedetails',
  templateUrl: './namedetails.component.html',
  styleUrls: ['./namedetails.component.css']
})
export class NameDetails implements OnInit {

@ViewChild("myTable") myTable:DataTableDirective;

  private nameList: any;
  private selectedName:string;

  private retrievedNames: any;
  dtTrigger: Subject<any> = new Subject();

  dtElement: DataTableDirective;

  dtOptions: DataTables.Settings = {};


  constructor(private _http:Http, private networkservice : NetworkService,private router: Router) { 
 }

  ngOnInit() {

      this.fetchFirstNames();

  }

  fetchFirstNames(){

    this.networkservice.getAllFirstNames()
          .subscribe(

            res => {
              console.log(res);
              this.nameList = res;
            });

  }

  fetchAllDetails(){

    this.networkservice.getAllNames(this.selectedName)
          .subscribe(

            res => {
              console.log(res);
              this.retrievedNames = res;
              this.myTable.dtInstance.then((dtInstance: DataTables.Api) => {
                  // Destroy the table first
                  dtInstance.destroy();
                  // Call the dtTrigger to rerender again
                  this.dtTrigger.next();
                });
            });

  }


  getData(){

      this.fetchAllDetails();
  }

}
Run Code Online (Sandbox Code Playgroud)

但是我不断收到以下错误 - “无法读取未定义的属性'then'”。我该如何解决?

Mol*_*och 6

您需要将以下方法添加到您的component.ts类中:

ngAfterViewInit() {
   this.dtTrigger.next();
}
Run Code Online (Sandbox Code Playgroud)

否则永远不会触发实例的初始化,因此永远不会首先创建 dtInstance;这就是它为空的原因。