угловая ошибка передачи данных при обновлении и привязке данных - PullRequest
1 голос
/ 03 мая 2019

Я пытаюсь создать таблицу данных и обновить данные в фильтре на applyFilter - но получаю ошибку как: TypeError: Cannot read property 'then' of undefined - Я понял, что способ, которым я интегрирую оба варианта, неправильный.

Кто-нибудь поможет мне найти правильный способ интегрировать то же самое?

вот мой полный код:

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...