【发布时间】:2019-08-25 04:30:26
【问题描述】:
我正在使用 Angular 从服务器读取 JSON 以使用 Datatables 显示它。 我正确读取文件并放入表中,但数据表的功能不起作用,它说“表中没有可用数据”和“显示 0 到 0 个条目”,但数据在那里。
插件及其依赖项已正确安装和导入。
这是 json 文件: http://dummy.restapiexample.com/api/v1/employees
-- empleado.ts
export class Empleado{
id :number;
employee_name :string;
employee_salary :number;
employee_age :number;
profile_image :string;
}
-- leer-empleados.service.ts
import { Injectable } from '@angular/core';
import { Empleado } from './empleado';
import {HttpClient} from '@angular/common/http';
import{Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LeerEmpleadosService {
private urlFichero = 'http://dummy.restapiexample.com/api/v1/employees';
getEmpleados() :Observable<Empleado[]> {
return this.http.get<Empleado[]>(this.urlFichero);
}
constructor(private http: HttpClient) { }
}
-- empleados.component.ts
import { Component, OnInit } from '@angular/core';
import { LeerEmpleadosService } from '../leer-empleados.service';
import { Empleado } from '../empleado';
@Component({
selector: 'app-empleados',
templateUrl: './empleados.component.html',
styleUrls: ['./empleados.component.css']
})
export class EmpleadosComponent implements OnInit {
empleados :Empleado[];
dtOptions :DataTables.Settings = {};
constructor( private leerService :LeerEmpleadosService) { }
ngOnInit() {
this.dtOptions = {
pagingType: "full_numbers",
pageLength: 5
}
this.getEmpleados();
}
getEmpleados() :void{
this.leerService.getEmpleados().subscribe(empleados => this.empleados = empleados);
}
}
-- empleados.component.html
<table datatable class="row-border hover" [dtOptions]="dtOptions">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Salario</th>
<th>Edad</th>
<th>Imagen</th>
</tr>
</thead>
<tbody *ngFor="let empleado of empleados">
<tr>
<td>{{empleado.id}}</td>
<td>{{empleado.employee_name}}</td>
<td>{{empleado.employee_salary}}</td>
<td>{{empleado.employee_age}}</td>
<div *ngIf="empleado.profile_image !=''; else elseImagen">
<td >{{empleado.profile_image}}</td>
</div>
<ng-template #elseImagen>
<td >No existe imagen</td>
</ng-template>
</tr>
</tbody>
</table>
-- app.module.ts
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { DataTablesModule } from 'angular-datatables';
import { AppComponent } from './app.component';
import { EmpleadosComponent } from './empleados/empleados.component';
@NgModule({
declarations: [
AppComponent,
EmpleadosComponent
],
imports: [
BrowserModule,
DataTablesModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
【问题讨论】:
-
控制台有错误吗?
-
@AlbertoL.Bonfiglio 不,控制台或代码中没有错误
-
您是否尝试过导入浏览器模块?
-
@AlbertoL.Bonfiglio 它是在 app.module.ts 中导入的
标签: json ajax angular datatable datatables