Datatable js в уничтожении объекта angular и не происходит обновления данных

#javascript #angular #datatable #datatables #angular-datatables

#javascript #angular #datatable #таблицы данных #angular-таблицы данных

Вопрос:

мы используем плагин datatablejs от angular для перечисления данных в нашем проектеhttps://l-lin.github.io/angular-datatables/#/getting-started ; существуют определенные события, когда данные необходимо обновить в datalist.

это работает с datatable js в jquery, где мы уничтожаем и перезагружаем его с помощью service.

с angular данные не меняются, если не щелкнуть какой-либо столбец или страница не будет перезагружена, что является проблемой для нас.

как это можно решить.

мы не хотим переходить к таблице материалов, так как есть много компонентов, где это необходимо исправить.

HTML:

    <!-- For tabs changes -->
                  <mat-tab-group>
                    <mat-tab label="Draft">
                      <div class="row">
                        <div class="col-md-12"><br />

                          <table datatable [dtOptions]="draftdtOptions" [dtTrigger]="dtTrigger"
                            class="mahait-table row-border hover">
                            <thead class="dt-head-center">


                            </thead>
                            <tbody class="dt-body-center">
                              <tr *ngFor="let createCal of createCals let row">
                                <td>
                                  <button type="button"
                                    class="btn btn-info btn-sm reject-button-alignment m-btn-body mt-1"
                                    style="margin-top:1px"
                                    (click)="open(row,$event,modal_edit_academic_calen_details)">Edit</button>
                                  <button type="submit" class="btn btn-danger reject-button-alignment mt-1"
                                    style="margin-left:5px;" (click)="openDelete(row,$event)">Delete</button><br />

                                  <button type="button" class="btn btn-update  reject-button-alignment mb-1"
                                    style="margin-top:4px"
                                    (click)="someClickHandler(row,$event,modal_update_event_details)">Update
                                    Events</button>

                                  <button type="button" (click)=openSendApprove(row,$event,modal_action_details)
                                    class="btn btn-success reject-button-alignment mb-1"
                                    style="margin-top:3px; margin-left:5px;">Send
                                    for
                                    Apporval</button>
                                </td>
                                <td>{{ createCal.AcademicYear }}</td>
                                <td> <a style="color:blue; cursor: pointer;"
                                    (click)="openView(row,$event,modal_view_academic_calen_details)">{{ createCal.CalendarCode }}</a>
                                </td>
                                <td>{{ createCal.EventCount }}</td>
                                <td>{{ createCal.CalandarType }}</td>
                                <td>{{ createCal.calendar_name }}</td>
                                <td>{{ createCal.created_on | date :  'yyyy-MM-dd'  }}</td>
                              </tr>
                            </tbody>

                          </table>
                        </div>
                      </div>
                    </mat-tab>
                    <mat-tab label="Send for Approval">
                      <div class="row">
                        <div class="col-md-12"><br />


                          <table id="second-table" datatable [dtOptions]="SendApproveldtOptions"
                            class="mahait-table row-border hover">
                            <thead class="dt-head-center"></thead>
                            <tbody class="dt-body-center">

                              <tr *ngFor="let sendTable of sendTables let row">


                                <td>{{  sendTable.AcademicYear }}</td>
                                <td><a style="color:blue; cursor: pointer;"
                                    (click)="openView(row,$event,modal_view_academic_calen_details)">{{ sendTable.CalendarCode }}</a>
                                </td>
                                <td>{{  sendTable.EventCount }}</td>
                                <td>{{  sendTable.CalandarType }}</td>
                                <td>{{  sendTable.calendar_name }}</td>
                              </tr>
                            </tbody>

                          </table>
                        </div>
                      </div>
                    </mat-tab>

                  </mat-tab-group>
                   <!-- End tabs changes -->
  

ts:

 // code starts here
            import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; // Data Table 
            import { FormArray, FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
            import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material';
            import { AcmServiceService } from '../../Shared/acm-service.service';
            import { NgbModalConfig, NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
            import { DatePipe } from '@angular/common';
            import Swal from 'sweetalert2';
            import { trigger, state, style, animate, transition } from '@angular/animations';
            import { HttpClient, HttpResponse } from '@angular/common/http';
            import { DataTableDirective } from 'angular-datatables'; // Data Table 
            import { Subject } from 'rxjs';
            import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
            import { MatTable } from '@angular/material/table';
            import { RouterLinkWithHref } from '@angular/router';
            import { Router } from '@angular/router';


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

            class createCal {
            AcademicYear: any;
            CalendarCode: any;
            EventCount: any;
            CalandarType: any;
            calendar_name: any;
            created_o_n: any;

            }


            class sendTable {
            AcademicYear: any;
            CalendarCode: any;
            EventCount: any;
            CalandarType: any;
            calendar_name: any;


            }
            export class AcmManageAcademicCalendarComponent implements AfterViewInit, OnDestroy, OnInit {

            @ViewChild(DataTableDirective)  // Data Table
            dtElement: DataTableDirective; // Data Table

            draftdtOptions: DataTables.Settings = {};    // First Data Table
            SendApproveldtOptions: DataTables.Settings = {}; // Second Data Table

            dtTrigger: Subject<boolean> = new Subject();     // First Data Table Trigger 

            dtTrigger2: Subject<boolean> = new Subject();    // Second Data Table Trigger 

            userData = { organisation_id: '1', requestStatusID: '1' };
            userData1 = { organisation_id: '1', requestStatusID: '2' };

            constructor(private Service: AcmServiceService, private http: HttpClient, private router: Router) {
            }
            ngOnInit() {
            this.dataTableAngulr();
            this.sendTabale();
            }

            //  FIrst Data Table Call 
            dataTableAngulr() {
            const that = this;

            this.draftdtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
            that.http
            .post<DataTablesResponse>(
            'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData), {}
            ).subscribe(resp => {
            that.createCals = resp.data;

            callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []

            });
            });

            },
            columns: [
            { data: '', title: 'Action', name: 'ay.academic_start_year' },
            { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
            { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
            { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
            { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
            { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' },
            { data: 'created_on', title: 'Modified Date', name: 'ac.created_on' }

            ],

            };
            }
            ngAfterViewInit(): void {
            this.dtTrigger.next();
            this.dtTrigger2.next();
            }

            ngOnDestroy(): void {
            this.dtTrigger.unsubscribe();
            this.dtTrigger2.unsubscribe();
            }

            rerender(): void {
            this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {

            dtInstance.destroy();
            this.dtTrigger.next();
            this.dtTrigger2.next();  // Second Table call for rerender
            });
            }


            //  Second Data Table 

            sendTabale() {
            const that = this;

            this.SendApproveldtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
            that.http
            .post<DataTablesResponse>(
            'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData1), {}
            ).subscribe(resp => {

            that.sendTables = resp.data;

            callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []

            });
            });

            },
            columns: [
            { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
            { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
            { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
            { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
            { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' }
            ]
            };
            }


            }

            Send_Approve_Adademic() {
            this.sendApproveObj = {
            RequestID: this.request_id,
            RequestStatusID: '2'
            }

            this.Service.create('AcademicCalandarStatusChange', this.sendApproveObj).subscribe(res => {
            if (res['status'] == true) {
            Swal.fire({
            type: 'success',
            title: ' Successfully Send Approvel',
            onClose: () => {
            this.GetAPI();

            this.modalRef3.close();
            }
            })
            }
            this.rerender(); // call The Rerender table
            })
            }
// code ends here
  

Ответ №1:

Похоже, это проблема с обнаружением изменений. Возможно, вам потребуется вручную определить изменения, вносимые вашим вызовом API.

Замените код вашего компонента на приведенный ниже:

 import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core'; // Data Table 
import { FormArray, FormControl, FormGroup, Validators, FormBuilder } from '@angular/forms';
import { MatSort, MatTableDataSource, MatPaginator } from '@angular/material';
import { AcmServiceService } from '../../Shared/acm-service.service';
import { NgbModalConfig, NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { DatePipe } from '@angular/common';
import Swal from 'sweetalert2';
import { trigger, state, style, animate, transition } from '@angular/animations';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { DataTableDirective } from 'angular-datatables'; // Data Table 
import { Subject } from 'rxjs';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { MatTable } from '@angular/material/table';
import { RouterLinkWithHref } from '@angular/router';
import { Router } from '@angular/router';


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

class createCal {
    AcademicYear: any;
    CalendarCode: any;
    EventCount: any;
    CalandarType: any;
    calendar_name: any;
    created_o_n: any;

}


class sendTable {
    AcademicYear: any;
    CalendarCode: any;
    EventCount: any;
    CalandarType: any;
    calendar_name: any;


}
export class AcmManageAcademicCalendarComponent implements AfterViewInit, OnDestroy, OnInit {

    @ViewChild(DataTableDirective)  // Data Table
    dtElement: DataTableDirective; // Data Table

    draftdtOptions: DataTables.Settings = {};    // First Data Table
    SendApproveldtOptions: DataTables.Settings = {}; // Second Data Table

    dtTrigger: Subject<boolean> = new Subject();     // First Data Table Trigger 

    dtTrigger2: Subject<boolean> = new Subject();    // Second Data Table Trigger 

    userData = { organisation_id: '1', requestStatusID: '1' };
    userData1 = { organisation_id: '1', requestStatusID: '2' };

    constructor(private Service: AcmServiceService, private http: HttpClient, private router: Router,
    private cdREf: ChangeDetectorRef) {
    }
    ngOnInit() {
        this.dataTableAngulr();
        this.sendTabale();
    }

    //  FIrst Data Table Call 
    dataTableAngulr() {
        const that = this;

        this.draftdtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
                that.http
                    .post<DataTablesResponse>(
                        'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData), {}
                    ).subscribe(resp => {
                        that.createCals = resp.data;

                        callback({
                            recordsTotal: resp.recordsTotal,
                            recordsFiltered: resp.recordsFiltered,
                            data: []

                        });

                        this.cdREf.markForCheck();
                    });

            },
            columns: [
                { data: '', title: 'Action', name: 'ay.academic_start_year' },
                { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
                { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
                { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
                { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
                { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' },
                { data: 'created_on', title: 'Modified Date', name: 'ac.created_on' }

            ],

        };
    }
    ngAfterViewInit(): void {
        this.dtTrigger.next();
        this.dtTrigger2.next();
    }

    ngOnDestroy(): void {
        this.dtTrigger.unsubscribe();
        this.dtTrigger2.unsubscribe();
    }

    rerender(): void {
        this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {

            dtInstance.destroy();
            this.dtTrigger.next();
            this.dtTrigger2.next();  // Second Table call for rerender
        });
    }


    //  Second Data Table 

    sendTabale() {
        const that = this;

        this.SendApproveldtOptions = {
            pagingType: 'full_numbers',
            pageLength: 4,
            serverSide: true,
            processing: true,
            search: true,

            ajax: (dataTablesParameters: any, callback) => {
                that.http
                    .post<DataTablesResponse>(
                        'http://fakeapiorg/api/acm/CalendarList', Object.assign(dataTablesParameters, this.userData1), {}
                    ).subscribe(resp => {

                        that.sendTables = resp.data;

                        callback({
                            recordsTotal: resp.recordsTotal,
                            recordsFiltered: resp.recordsFiltered,
                            data: []

                        });
                        this.cdREf.markForCheck();
                    });

            },
            columns: [
                { data: 'AcademicYear', title: 'Academic Year', name: 'academic_start_year' },
                { data: 'CalendarCode', title: 'Calendar ID', name: 'calendar_id' },
                { data: 'EventCount', title: 'Events Count', name: 'EventCount' },
                { data: 'CalandarType', title: 'Academic Calendar Type', name: 'ct.taxonomy_name' },
                { data: 'calendar_name', title: 'Calendar Name', name: 'ac.calendar_name' }
            ]
        };
    }


}

Send_Approve_Adademic() {
    this.sendApproveObj = {
        RequestID: this.request_id,
        RequestStatusID: '2'
    }

    this.Service.create('AcademicCalandarStatusChange', this.sendApproveObj).subscribe(res => {
        if (res['status'] == true) {
            Swal.fire({
                type: 'success',
                title: ' Successfully Send Approvel',
                onClose: () => {
                    this.GetAPI();

                    this.modalRef3.close();
                }
            })
        }
        this.rerender(); // call The Rerender table
    })
}
  

Комментарии:

1. мы пробовали это, но это не работает, есть ли что-то еще, что можно сделать?