数据表显示使用Angular表中没有可用数据

Ram*_*har 5 datatable typescript angular

当我试图在angular js中显示数据表时。它显示表中没有可用数据,但表中有4条记录。请参见下面的屏幕截图。

在此处输入图片说明

这就是我所做的。

user.component.ts

import { Component, OnInit } from '@angular/core';

import { UserModel }         from './user-model';
import { UserService }       from './user.service';
declare var $ :any;

@Component({
  selector: 'user-page',
  template: require('./user.component.html'),
  providers: [ UserService ]
})

export class UserComponent implements OnInit {

  data: any;
  errorMessage: string;

 constructor(private userService:UserService){ }

 ngOnInit() { 
  this.getUsers();
 }

 getUsers() {  
 this.userService.getUsers()
                 .subscribe(
                   users => {this.data = users; 
                              $(function(){
                               $("#user-table").DataTable();
                              });
                            },
                   error =>  this.errorMessage = <any>error);
  }
}
Run Code Online (Sandbox Code Playgroud)

user.service.ts

import { Injectable }              from '@angular/core';
import { Http, Response }          from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { UserModel } from './user-model';

@Injectable()
export class UserService {
      private usersUrl = 'http://localhost/larang/public/api/users';  
constructor (private http: Http) {}

getUsers(): Observable<UserModel[]> { 
 return this.http.get(this.usersUrl)
                .map(this.extractData)
                .catch(this.handleError);
}


private extractData(res: Response) { 
  let body = res.json();

  return body.data || { };
}

private handleError (error: Response | any) { console.log(error);

 let errMsg: string;
 if (error instanceof Response) {
  const body = error.json() || '';
  const err = body.error || JSON.stringify(body);
  errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
 } else {
   errMsg = error.message ? error.message : error.toString();
 }
console.error(errMsg);
return Observable.throw(errMsg);
 }
}
Run Code Online (Sandbox Code Playgroud)

user.component.html

<table id="user-table" class="table table-bordered table-hover">
 <thead>
      <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Added On</th>
      </tr>
 </thead>
 <tbody>
       <tr *ngFor="let item of data">
         <td>{{item.name}}</td>
         <td>{{item.email}}</td>
         <td>{{item.added}}</td>
       </tr>
 </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

this.data看起来像这样

[
 {"name":"John Doe","email":"john.doe@gmail.com","added":"2017-04-26"},
 {"name":"Ramkishan","email":"Ramkishan@gmail.com","added":"2017-04-26"},
 {"name":"Jason Bourne","email":"jason@gmail.com","added":"2017-04-26"},
 {"name":"RK","email":"ramkishan.suthar@ranosys.com","added":"2017-04-26"}
]
Run Code Online (Sandbox Code Playgroud)

我做错了,请帮忙。对于像我这样的Angular JS新手来说,这将非常有用。

ste*_*ane 15

在您的user.component.ts 中,声明您的数据变量为空以初始化它。我不知道为什么,但是当我刷新页面时遇到了同样的问题。我认为数据丢失了,所以你需要初始化它。也许数据表需要知道有一个数组,并且在填充它之后它就可以工作了。

    ngOnInit(){
        this.data = [];
        this.getUsers();
    }
Run Code Online (Sandbox Code Playgroud)

我错了

您必须重新渲染数据表,因为如果重新渲染初始化会引发错误,这就是为什么尽管表中有数据但仍显示“无可用数据”的消息。

更新

在您的组件中,声明此变量:

  @ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
  dtOptions: DataTables.Settings = {};
  dtTrigger: Subject<any> = new Subject();
Run Code Online (Sandbox Code Playgroud)

从您拥有的任何服务中提取数据后:

this.officeSrv.getAll().subscribe((data) => {
  console.log('----> office service : get all data', data);
  this.offices = data.offices;

  // ADD THIS
  this.dtTrigger.next();

}, (err) => {
  console.log('-----> err', err);
})
Run Code Online (Sandbox Code Playgroud)

如果有修改直接在同一个数据表中进行修改而不改变页面创建并调用此函数

rerender(): void {
 this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
   // Destroy the table first
   dtInstance.destroy();
   // Call the dtTrigger to rerender again
   this.dtTrigger.next();
 });
}
Run Code Online (Sandbox Code Playgroud)

在您的组件中使用此库:

    import { DataTableDirective } from 'angular-datatables';
Run Code Online (Sandbox Code Playgroud)

在您的应用模块中:

    import { DataTablesModule } from 'angular-datatables';
Run Code Online (Sandbox Code Playgroud)

并声明:

    imports: [
           ...,
           DataTablesModule
Run Code Online (Sandbox Code Playgroud)

最后是你的模板(HTML):

   <table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-hover table-striped table-bordered" cellspacing="0"
      width="100%">
      <thead>
        <tr>
          <th>Nom</th>
          <th>Adresse</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let office of offices">
          <td>{{office.name}}</td>
          <td>{{office.adress}}</td>
          <td>
            <div class="btn-group">
              <button type="button" class="btn btn-block btn-info">Action</button>
              <button type="button" class="btn btn-primary btn-outline-info dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"
                aria-haspopup="true" aria-expanded="false">
              <span class="sr-only">Toggle Dropdown</span>
            </button>
              <div class="dropdown-menu">
                <a class="dropdown-item" (click)="update(office._id)">Mettre à jour</a>
                <a class="dropdown-item" (click)="delete(office._id)">Supprimer</a>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
Run Code Online (Sandbox Code Playgroud)

希望这有帮助

源代码:https : //l-lin.github.io/angular-datatables/#/advanced/rerender


Nik*_*kar 11

所以在我的情况下,DataTables 在我得到服务器的响应之前就被激活了。我刚刚为我的桌子添加了 *ngIf 并且它对我有用。像下面。

<table *ngIf="dataService.users" datatable="ng" [dtOptions]="dtOptions">
Run Code Online (Sandbox Code Playgroud)

  • 它在 if 条件下工作得很好,谢谢兄弟 (2认同)

小智 5

添加超时以解决您的问题。

 setTimeout(function () {
  $(function () {
    $('#user-table').DataTable();
  });
}, 3000);
Run Code Online (Sandbox Code Playgroud)

参考我在 youtube 上找到的这个视频链接 https://www.youtube.com/watch?v=78X8ZRU9Hy8