Так что я использую DataTables в проекте angular и использую метод AJAX для получения данных с сервера. Все это прекрасно работает, пока я не выдаю refre sh для таблицы.
Я ожидал, что это просто уничтожит таблицу и запустит то же самое, что и при первой загрузке таблицы. в, но он производит странные дополнительные строки с [объектом, объектом] в них.
Изображение ниже - это то, как оно выглядит при начальной загрузке:
![enter image description here](https://i.stack.imgur.com/1498K.png)
Итак, я нажимаю кнопку New Branch, которая загружает модальное поле, заполняет форму, сохраняет новую ветвь и затем подключается к событию close модального окна. Я говорю таблице перезагрузить, и это результат:
![enter image description here](https://i.stack.imgur.com/MFhgQ.png)
Ожидаемый результат заключается в том, что он просто уничтожает таблицу, снова запускает вызов ajax и восстанавливает таблицу, как это было изначально.
Вот код TS:
import {Component, OnInit, ViewChild} from '@angular/core';
import {ApiResponseInterface} from "../../../interfaces/apiResponse.interface";
import {CompanyTableInterface} from "../../../interfaces/company.interface";
import {BranchInterface} from "../../../interfaces/branch.interface";
import {ApiService} from "../../../services/api.service";
import {NgbModal} from "@ng-bootstrap/ng-bootstrap";
import {NewBranchModalComponent} from "../../../components/modals/new-branch-modal/new-branch-modal.component";
import {DataTableDirective} from "angular-datatables";
import {Subject} from "rxjs";
@Component({
selector: 'app-branchlisting',
templateUrl: './branchlisting.component.html',
styleUrls: ['./branchlisting.component.scss']
})
export class BranchlistingComponent implements OnInit {
@ViewChild(DataTableDirective,{static:false}) tableElement: DataTableDirective;
public tableOptions: DataTables.Settings = {};
public branches: BranchInterface[] = [];
public tableTrigger: Subject<any> = new Subject();
constructor(private api: ApiService, private modalService: NgbModal) { }
ngOnInit() {
this.tableOptions = {
serverSide: true,
processing: false,
pagingType: 'full_numbers',
pageLength: 10,
ajax: (dataTablesParameters: any, callback) => {
this.api.post('branches/listing', dataTablesParameters).subscribe((response: ApiResponseInterface) => {
console.log(response);
this.branches = <BranchInterface[]>response.data.branches;
callback({
recordsTotal: <number>response.data.recordsTotal,
recordsFiltered: <number>response.data.recordsFiltered,
data: <CompanyTableInterface[]>response.data.branches,
draw: response.data.draw,
pageLength: response.data.pageLength,
search: response.data.search,
order: response.data.order,
column: response.data.columns
});
});
},
columns: [
{
data: null,
orderable: false,
searchable: false
},
{
data: 'name',
orderable: false,
searchable: false
},
{
data: null,
orderable: false,
searchable: false
},
{
data: 'telephone',
orderable: false,
searchable: false
},
{
data: 'mobile',
orderable: false,
searchable: false
},
{
data: 'email',
orderable: false,
searchable: false
},
{
data: null,
orderable: false,
searchable: false
}
]
}
}
ngAfterViewInit(){
this.tableTrigger.next();
}
newBranchModal(){
const modal = this.modalService.open(NewBranchModalComponent,{size:'xl'});
modal.result.then((branches: BranchInterface[])=>{
this.tableElement.dtInstance.then((dtIn: DataTables.Api)=>{
dtIn.destroy();
this.tableTrigger.next();
});
});
}
editBranchModal(branch: BranchInterface){
const modal = this.modalService.open(NewBranchModalComponent,{size:'xl'});
modal.componentInstance.branch = branch;
}
deleteBranch(branch: BranchInterface){
if(confirm("Are you sure?")){
}
}
}
И html:
<div class="page-title mb-30">
<div class="row">
<div class="col-sm-6">
<h4 class="mb-0">Branch Management</h4>
</div>
<div class="col-sm-6 text-right">
<button type="button" class="btn btn-primary" (click)="newBranchModal()">New Branch</button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-30">
<div class="card">
<div class="card-body">
<div class="table-responsive companyListingTable">
<table class="table mb-0" datatable [dtOptions]="tableOptions" [dtTrigger]="tableTrigger">
<thead>
<tr>
<th style="width: 20px;"> </th>
<th>Branch Name</th>
<th>Branch Address</th>
<th>Contact Telephone</th>
<th>Contact Mobile</th>
<th>Contact Email</th>
<th> </th>
</tr>
</thead>
<tbody *ngIf="branches?.length > 0">
<tr *ngFor="let branch of branches">
<td style="width:20px;">
<input type="checkbox"/>
</td>
<td>
{{ branch.name }}
</td>
<td>
{{ branch.buildingName }}<br/>
{{ branch.buildingNumber }} {{ branch.streetName }}<br/>
{{ branch.town }}<br/>
{{ branch.county }}<br/>
{{ branch.postcode }}
</td>
<td>
{{ branch.telephone ? branch.telephone : 'N/A' }}
</td>
<td>
{{ branch.mobile ? branch.mobile : 'N/A' }}
</td>
<td>
{{ branch.email ? branch.email : 'N/A' }}
</td>
<td class="text-right">
<a class="dropdown-toggle-split mb-20" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="ti-menu"></i></a>
<div class="dropdown-menu" x-placement="bottom-start">
<a class="dropdown-item" href="javascript:void(0)" (click)="editBranchModal(branch)">Edit Branch</a>
<a class="dropdown-item" href="javascript:void(0)" (click)="deleteBranch(branch)">Delete Branch</a>
</div>
</td>
</tr>
</tbody>
<tbody *ngIf="branches?.length === 0">
<tr>
<td colspan="7" class="no-data-available text-center" >No Branches Available</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>