刷新和数据绑定时出现角度数据表抛出错误

时间:2019-05-03 06:54:45

标签: angular angular7 angular-datatables

我正在尝试创建数据表并在applyFilter处的过滤器上刷新数据-但由于出现以下错误:TypeError: Cannot read property 'then' of undefined-我知道我整合这两个选项的方式是错误的。 / p>

有人帮助我找到一种正确的整合方式吗?

这是我的完整代码:

import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables';
import { map } from 'rxjs/operators';
import { Subject } from 'rxjs';

class Person {
    id: number;
    firstName: string;
    lastName: string;
}

class DataTablesResponse {
    data: any[];
    draw: number;
    recordsFiltered: number;
    recordsTotal: number;
}

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

    @ViewChild(DataTableDirective)
    datatableElement: DataTableDirective;
    dtOptions: DataTables.Settings = {};
    dtTrigger: Subject<any> = new Subject();

    showmenuOne:boolean = false;
    showmenuTwo:boolean = false;
    showmenuThr:boolean = false;

    tableData =  [
    {
      "id": 860,
      "firstName": "Superman",
      "lastName": "Yoda",
      "category": "Academic Honesty"
    },
    {
      "id": 870,
      "firstName": "Foo",
      "lastName": "Whateveryournameis",
      "category": "Setup & configuration"
    },
    {
      "id": 590,
      "firstName": "Toto",
      "lastName": "Titi",
      "category": "Academic Honesty"
    },
    {
      "id": 803,
      "firstName": "Luke",
      "lastName": "Kyle",
      "category": "Academic Honesty"
    },
    {
      "id": 474,
      "firstName": "Toto",
      "lastName": "Bar",
      "category": "Academic Honesty"
    },
    {
      "id": 476,
      "firstName": "Zed",
      "lastName": "Kyle",
      "category": "School preparation"
    },
    {
      "id": 464,
      "firstName": "Cartman",
      "lastName": "Kyle",
      "category": "Academic Honesty"
    },
    {
      "id": 505,
      "firstName": "Superman",
      "lastName": "Yoda",
      "category": "Setup & configuration"
    },
    {
      "id": 308,
      "firstName": "Louis",
      "lastName": "Kyle",
      "category": "Academic Honesty"
    },
    {
      "id": 184,
      "firstName": "Toto",
      "lastName": "Bar",
      "category": "Student Management"
    },
    {
      "id": 411,
      "firstName": "Luke",
      "lastName": "Yoda",
      "category": "School preparation"
    },
    {
      "id": 154,
      "firstName": "Luke",
      "lastName": "Moliku",
      "category": "Academic Honesty"
    },
    {
      "id": 623,
      "firstName": "Someone First Name",
      "lastName": "Moliku",
      "category":"School preparation"
    },
    {
      "id": 499,
      "firstName": "Luke",
      "lastName": "Bar",
      "category":"Setup & configuration"
    },
    {
      "id": 482,
      "firstName": "Batman",
      "lastName": "Lara",
      "category": "Academic Honesty"
    },
    {
      "id": 255,
      "firstName": "Louis",
      "lastName": "Kyle",
      "category": "Access & inclusion"
    },
    {
      "id": 772,
      "firstName": "Zed",
      "lastName": "Whateveryournameis",
      "category": "Access & inclusion"
    }
  ]


    datas:any;

    currentCategory:string;
    // persons: Person[];
    categoryListCopy = null;
    tableDataCopy=null;

    categoryList = [
        "Select All",
        "Academic Honesty",
        "Setup & configuration",
        "School preparation",
        "Student Management",
        "Access & inclusion"
    ];

    constructor(private http: HttpClient) {}

    getDatas(){
       return this.http.get('data/data.json').subscribe(values =>  {
           this.datas = values;
       });
    }

    ngOnInit() {

        this.categoryListCopy = this.categoryList;
        this.tableDataCopy = this.tableData;

        const that = this;
        this.dtOptions = {

            columns:[{
                data: 'id'
            }, {
                data: 'firstName'
            }, {
                data: 'lastName'
            }],
            pagingType: 'full_numbers',
            pageLength: 10,
            serverSide: false,
            processing: true,
            data: this.tableData

        };



        }

        ngAfterViewInit(): void {
            this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
                dtInstance.columns().every(function () {
                    const that = this;
                    $('input', this.footer()).on('keyup change', function () {
                        if (that.search() !== this['value']) {
                            that
                            .search(this['value'])
                            .draw();
                        }
                    });
                });

            });
             this.dtTrigger.next();

        }

        showMenu(menu){
            this[menu] = !this[menu];
        }

        onFilterChange(event:string){

            this.categoryList = this.categoryListCopy;
            const result = this.categoryList.filter((data) =>  JSON.stringify(data).toLowerCase().indexOf(event.toLowerCase()) !== -1);
            this.categoryList = result;

        }

        changeCategory(category:string) {
            this.currentCategory = category;
        }

        ngOnDestroy(): void {
        // Do not forget to unsubscribe the event
        this.dtTrigger.unsubscribe();
       }

        applyFilter(): void {

            this.tableData = this.tableDataCopy;
            let array = [];
            array.push(this.currentCategory);
            const result = this.tableData.filter(x => array.includes(x.category));
            this.showMenu('showmenuOne');

            console.log('result', result);

            this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
                // Destroy the table first
                dtInstance.destroy();
                $('#mytable').DataTable().destroy();
                this.tableData = result; //updating data not works
                // Call the dtTrigger to rerender again
                this.dtTrigger.next();
            });

        }

    }

我的模板:

<div class="container">
    <table id="mytable" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
      <thead>
        <tr>
          <th>
            <div class="sub-list">
              <span (click)="showMenu('showmenuOne')">ID&#183;&#183;&#183;</span>
              <div class="filter-list" [ngClass]="{show:showmenuOne}">
                  <span><a (click)="showMenu('showmenuOne')" class="sort" href="#">Ascending</a></span>
                  <span><a (click)="showMenu('showmenuOne')" class="sort" href="#">Decending</a></span>
                  <span>Filter</span>
                  <span>
                    <input type="text" name="" width="100%" (input)="onFilterChange($event.target.value)" style="border: 1px solid red">
                  </span>
                  <ul>
                    <li *ngFor="let category of categoryList"><input value={{category}} (change)="changeCategory($event.target.value)" type="checkbox" name="" id=""> {{category}}</li>
                  </ul>
                  <div class="filter-decion">
                      <button (click)="showMenu('showmenuOne')">Cancel</button>
                      <button (click)="applyFilter()">Apply</button>
                  </div>
              </div>
            </div>
          </th>
          <th>
            <div class="sub-list">
              <span><a class="sort" href="#">First name</a> &#183;&#183;&#183;</span>
            </div>
          </th>
          <th>
             <div class="sub-list">
              <span><a class="sort" href="#">Last name</a> &#183;&#183;&#183;</span>
            </div>
          </th>
      </tr>
  </thead>
   <tbody class="col_filter" >
         <tr>
          <td><input type="text" placeholder="Search ID" name="search-id"/></td>
          <td><input type="text" placeholder="Search first name" name="search-first-name"/></td>
          <td><input type="text" placeholder="Search last name" name="search-last-name"/></td>
         </tr>
  </tbody>

  <tbody *ngIf="persons?.length != 0">
      <tr *ngFor="let person of persons">
          <td>{{ person.id }}</td>
          <td>{{ person.firstName }}</td>
          <td>{{ person.lastName }}</td>
      </tr>
  </tbody>

  <tbody *ngIf="persons?.length == 0">
    <tr>
      <td colspan="3" class="no-data-available">No data!</td>
  </tr>
  </tbody>

  </table>

</div>

0 个答案:

没有答案