首页 > 解决方案 > 数据表中只允许使用数组和可迭代对象

问题描述

我正在尝试使用数据表进行 crud 操作。当我单击提交按钮进行创建时,它向我显示错误Only arrays and iterables are allowed in datatable。控制台在代码行所在的 component.html 中显示错误

组件.html

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" 
class="row-border hover"> //This is where the console shows error

<tbody>
  <tr *ngFor="let person of persons">
   <td>{{ person.id }}</td>
   <td>{{ person.name}}</td>
   </tr>
</tbody>

组件.ts

 dtOptions: DataTables.Settings = {};
 persons: any = [];

 // We use this trigger because fetching the list of persons can be 
 quite long,
 // thus we ensure the data is fetched before rendering

 dtTrigger: any = new Subject();

 constructor(private Authentication:AuthService) { }


 ngOnInit(): void {

 this.getRolesFromServices();
this.dtOptions = {
  pagingType: 'full_numbers',
  pageLength: 4
};
this.Authentication.getRoleData()
  .map(this.extractData)
  .subscribe(persons => {
    this.persons = persons;
    // Calling the DT trigger to manually render the table
    this.dtTrigger.next();
  });

 }

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

 private extractData(res: Response) {
 const body = res;
 return body || {};
 }

我能够创建数据并且它确实被添加但它没有显示在页面中。它仅在我刷新时显示。

标签: angularangular5angular6angular-datatables

解决方案


如果getRoleData返回null或空字符串或一般的 falsy 结果 extractData将返回对象而不是空数组

private extractData(res: Response) {
 const body = res;
 return body || {}; // this cause only arrays and iterables are allowed in datatable
 }

像这样改变

private extractData(res: Response) {
 const body = res;
 return body || [];
 }

推荐阅读