数据表使用 Angular 显示表中没有可用数据 [英] Data table is showing no data available in table using Angular

查看:19
本文介绍了数据表使用 Angular 显示表中没有可用数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这就是我所做的.

user.component.ts

import { Component, OnInit } from '@angular/core';从'./user-model'导入{用户模型};从 './user.service' 导入 { UserService };声明 var $ :any;@零件({选择器:'用户页面',模板:需要('./user.component.html'),提供者:[ UserService ]})导出类 UserComponent 实现 OnInit {数据:任何;错误消息:字符串;构造函数(私有用户服务:用户服务){}ngOnInit() {this.getUsers();}获取用户(){this.userService.getUsers().订阅(用户 =>{this.data = 用户;$(函数(){$("#user-table").DataTable();});},错误 =>this.errorMessage = <any>error);}}

user.service.ts

import { Injectable } from '@angular/core';从@angular/http"导入 { Http, Response };从 '@angular/http' 导入 { Headers, RequestOptions };从 'rxjs/Observable' 导入 { Observable };导入 'rxjs/add/operator/catch';导入 'rxjs/add/operator/map';从'./user-model'导入{用户模型};@Injectable()导出类 UserService {private usersUrl = 'http://localhost/larang/public/api/users';构造函数(私有 http: Http){}getUsers(): Observable{返回 this.http.get(this.usersUrl).map(this.extractData).catch(this.handleError);}私人提取数据(资源:响应){让 body = res.json();返回 body.data ||{ };}private handleError (error: Response | any) { console.log(error);让 errMsg: 字符串;如果(错误实例响应){const body = error.json() ||'';const 错误 = body.error ||JSON.stringify(body);errMsg = `${error.status} - ${error.statusText ||''} ${错误}`;} 别的 {errMsg = 错误消息?error.message : error.toString();}控制台错误(错误消息);返回 Observable.throw(errMsg);}}

user.component.html

<头><tr><th>姓名</th><th>电子邮件</th><th>添加于</th></tr></thead><tr *ngFor="让数据项"><td>{{item.name}}</td><td>{{item.email}}</td><td>{{item. added}}</td></tr></tbody>

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"}]

我做错了什么,请帮忙.对我这样的 Angular JS 新手很有帮助.

解决方案

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

 ngOnInit(){this.data = [];this.getUsers();}

我错了

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

更新

在你的组件中,声明这个变量:

 @ViewChild(DataTableDirective)dtElement:数据表指令;dtOptions: DataTables.Settings = {};dtTrigger:主题<任何>= 新主题();

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

this.officeSrv.getAll().subscribe((data) => {console.log('----> office service : get all data', data);this.offices = data.offices;//添加这个this.dtTrigger.next();}, (错误) =>{console.log('-----> 错误', 错误);})

如果有修改直接在同一个datatable中修改而不改变页面创建并调用这个函数

rerender(): void {this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {//先销毁表dtInstance.destroy();//调用 dtTrigger 重新渲染this.dtTrigger.next();});}

在你的组件中使用这个库:

 import { DataTableDirective } from 'angular-datatables';

在您的应用模块中:

 import { DataTablesModule } from 'angular-datatables';

并声明:

 导入:[...,数据表模块

最后是您的模板 (HTML):

 <头><tr><th>Nom</th><th>地址</th><th>动作</th></tr></thead><tr *ngFor="let office of office"><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">切换下拉菜单</span><div class="下拉菜单"><a class="dropdown-item" (click)="update(office._id)">Mettre à jour</a><a class="dropdown-item" (click)="delete(office._id)">Supprimer</a>

</td></tr></tbody>

希望能帮到你

src : https://l-lin.github.io/角度数据表/#/advanced/rerender

When I was trying to show data table in angular js. It shows no data available in table but there are 4 records in table. See screenshot below.

Here's what I did.

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);
  }
}

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);
 }
}

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>

this.data looks like this

[
 {"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"}
]

What I am doing wrong please help. It will be very helpful for newbies in Angular JS like me.

解决方案

In your user.component.ts, declare your data var empty to initialize it. I don't know why but I had the same problem when I refresh the page. I think the data is lost so you need to initialize it. Maybe datatable needs to know there is an Array and after you fill it it's working.

    ngOnInit(){
        this.data = [];
        this.getUsers();
    }

I WAS WRONG

You have to rerender the datatable because if you rerender the initialisation throw an error, that's why you have the message saying "no data available" despite you have in the table.

UPDATE

In your component, declare this variable:

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

after you pull your data from whatever service you have:

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);
})

If you have modification to make modification directly in the same datatable without changing the page create and call this function

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

Use this library in your component:

    import { DataTableDirective } from 'angular-datatables';

In your app module:

    import { DataTablesModule } from 'angular-datatables';

And declare this :

    imports: [
           ...,
           DataTablesModule

And finally for your templating (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>

Hope that's help

src : https://l-lin.github.io/angular-datatables/#/advanced/rerender

这篇关于数据表使用 Angular 显示表中没有可用数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆