У меня есть приложение Angular с простой функциональностью CRUD. Я проверил свои данные с помощью статической таблицы HTML, и это работает. Сейчас я использую каркас таблицы данных под названием Angular table table.
Ссылка: https://l -lin.github.io / angular-datatables / # / welcome
Я могу Создать , Читать и Удалить запись, но после этого действия я получаю сообщение об ошибке:
Предупреждение DataTables: идентификатор таблицы = DataTables_Table_0 - Невозможно повторно инициализировать
Таблица данных. Для получения дополнительной информации об этой ошибке, пожалуйста, см.
http://datatables.net/tn/3
Я пробовал несколько решений, таких как приведенная ссылка и другие сообщения о переполнении стека, например:
Получение ошибки в Angular 5 Datatables: не может повторно инициализировать DataTable
https://l -lin.github.io / Угловой-DataTables / # / основной / угловой способ
https://l -lin.github.io / угловатые-DataTables / # / расширенный / * 1034 повторно вызывать *
Это мой код в car-component.js , и я использую car-services.js для всех моих HTTP-вызовов.
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { CarService } from '../services/carservices/car.service';
import { CarVM } from '../viewmodels/car/car-vm';
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';
@Component({
selector: 'app-car',
templateUrl: './car.component.html',
styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
FormCar: any;
countrecords: any;
Carid: number = 0;
dtTrigger: Subject<any> = new Subject();
dtElement: DataTableDirective;
allCars: CarVM[];
dtOptions: DataTables.Settings = {};
constructor(private formbuilder: FormBuilder, private carservice: CarService) { }
ngOnInit() {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 5,
};
this.GetCar();
this.GetCarCount();
this.FormCar = this.formbuilder.group({
CarId: ['', Validators.required],
Brand: ['', Validators.required],
Model: ['', Validators.required],
Color: ['', Validators.required],
TopSpeed: ['', Validators.required],
});
}
AddCar(CarVM: CarVM) {
CarVM.CarId = this.Carid;
this.carservice.CreateCar(CarVM).subscribe(() => {
this.GetCar();
this.GetCarCount();
this.Reset();
this.Carid = 0;
})
}
GetCar() {
this.carservice.getAllCars().subscribe(res => {
this.allCars = res;
this.dtTrigger.next();
})
}
GetCarCount() {
this.countrecords = this.carservice.getCount();
}
EditCar(car: CarVM) {
this.carservice.updateCar(car).subscribe(Response => {
this.Carid = Response.CarId;
this.FormCar.controls['Brand'].setValue(Response.Brand);
this.FormCar.controls['Model'].setValue(Response.Model);
this.FormCar.controls['Color'].setValue(Response.Color);
this.FormCar.controls['TopSpeed'].setValue(Response.TopSpeed);
})
}
DeleteCar(CarId: string) {
if (confirm("Are you sure?")) {
this.carservice.deleteCar(CarId).subscribe(() => {
this.GetCar();
this.GetCarCount();
})
}
}
Reset() {
this.FormCar.reset();
}
}
А это моя HTML-страница из машины:
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th>Id</th>
<th>Brand</th>
<th>Model</th>
<th>Color</th>
<th>Speed</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let car of allCars">
<td>{{car.carId}}</td>
<td>{{car.brand}}</td>
<td>{{car.model}}</td>
<td>{{car.color}}</td>
<td>{{car.topSpeed }}</td>
<td>
<button type="button" class="btn btn-danger mr-1" (click)="DeleteCar(car.carId)">Delete</button>
</td>
</tr>
</tbody>
</table>
ПРИМЕЧАНИЕ:
Я использовал Angular версию, а не JQuery версию!
Может ли кто-нибудь указать мне правильное направление?