typeError:无法读取属性' dtInstance'未定义的

时间:2017-05-17 13:03:15

标签: angular angular2-services angular-datatables

我试图通过angular2实现路易斯·林的角度数据表。

当我尝试获取Datatable的实例时,它会给出 typeError:无法读取属性' dtInstance'未定义的

我引用了here

中的文档中的步骤

下面是我的代码

import { Component, OnInit,AfterViewInit,ViewChild } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Rx';
import { DataTableDirective } from 'angular-datatables';
import { EmployeeService } from '../services/employee.service';
import { Employee} from "app/services/employee";
@Component({
selector: 'app-employees',
templateUrl: './employees.component.html',
styleUrls: ['./employees.component.css']
})

 export class EmployeesComponent implements OnInit {  
 employees: Employee[];
 private datatableElement: DataTableDirective;
 dtOptions: DataTables.Settings = {};
 constructor(
 private employeeservice:EmployeeService,
 private route: ActivatedRoute,
 private router: Router,
 ) { 

 }
 ngOnInit(): void {
 this.getEmployee(); 
 this.dtOptions = {
  paginationType: 'full_numbers',
  displayLength: 5
  };
 }
displayToConsole(datatableElement: DataTableDirective): void 
{
datatableElement.dtInstance.then((dtInstance: DataTables.Api) => 
console.log(dtInstance));
} 
getEmployee(){
this.employeeservice.getEmployees()
.subscribe(
    employees =>{ 
        this.employees = employees; 
        console.log(this.employees);
    (error:Response) => console.log(error)
  },
 )     
}

 deleteEmployee(employee){
 if (confirm("Are you sure you want to delete Employee ?")) {
 console.log(employee.id);
  var index = this.employees.indexOf(employee);
  this.employees.splice(index, 1);

  this.employeeservice.deleteEmployee(employee.id)
    .subscribe(
      data =>{
        this.emp_data = employee;
      },
      err => {
        alert("Could not delete employee.");
        // Revert the view back to its original state
        this.employees.splice(index, 0, employee);
      },
      () => this.router.navigate(['/employees'])
      );
  }
 }
}

1 个答案:

答案 0 :(得分:1)

看起来您在使用datatableElement之前有数据,您可以使用promise来确保它有数据。