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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44940021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:41:31  来源:igfitidea点击:

Data table is showing no data available in table using Angular

angulartypescriptdatatable

提问by Ramkishan Suthar

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.

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

enter image description here

在此处输入图片说明

Here's what I did.

这就是我所做的。

user.component.ts

用户组件.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

用户服务.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

用户组件.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.datalooks like this

this.data看起来像这样

[
 {"name":"John Doe","email":"[email protected]","added":"2017-04-26"},
 {"name":"Ramkishan","email":"[email protected]","added":"2017-04-26"},
 {"name":"Jason Bourne","email":"[email protected]","added":"2017-04-26"},
 {"name":"RK","email":"[email protected]","added":"2017-04-26"}
]

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

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

回答by stephane

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.

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

    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):

最后是你的模板(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

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

回答by Nikhil Bhandarkar

So in my case DataTables are getting activated before I got the response from the server. I just added *ngIf for my table and it worked for me. Like below.

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

<table *ngIf="dataService.users" datatable="ng" [dtOptions]="dtOptions">

回答by hasitha lakthilina

Added Time out for solve your problem.

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

 setTimeout(function () {
  $(function () {
    $('#user-table').DataTable();
  });
}, 3000);

refer this video link I found on youtube https://www.youtube.com/watch?v=78X8ZRU9Hy8

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

回答by Akshay L

Using a Timeout function is a bad practice. As you are using angular, the best way to solve this is by using change detection.

使用超时函数是一种不好的做法。当您使用 angular 时,解决此问题的最佳方法是使用change detection.

First create this instance by adding it in the constructor like this,

首先通过像这样在构造函数中添加它来创建这个实例,

... constructor(private chRef: ChangeDetectorRef) { } ...in the component where you want to use datatables.

... constructor(private chRef: ChangeDetectorRef) { } ...在要使用数据表的组件中。

Now use the detectChangesfunction so that angular waits till something is changed(in your case, till the table is generated properly)

现在使用该detectChanges函数,以便 angular 等待某些内容发生更改(在您的情况下,直到正确生成表)

ngOnInit() { 
  ... 
   this.chRef.detectChanges();
   const table: any = $('table');
   this.dataTable = table.DataTable(); 
  ...
 }

So that one line this.chRef.detectChanges()really fixes the issue.

所以这一行this.chRef.detectChanges()确实解决了这个问题。

回答by Thomas Gicquel

  1. add this code on the constructor:

    private changeDetectorRef: ChangeDetectorRef
    
  2. On theuser.component.ts -> getUsers(), you can add a complete function:

    this.userService.getUsers().subscribe(users => {
        this.data = users;
    },
    error => { this.errorMessage = <any>error },
    () => {
        //Complete
        this.changeDetectorRef.detectChanges();
        const table: any = $("#user-table").DataTable();
        this.dataTable = table.DataTable();
    });
    
  1. 在构造函数上添加此代码:

    private changeDetectorRef: ChangeDetectorRef
    
  2. 在 上user.component.ts -> getUsers(),您可以添加一个完整的功能:

    this.userService.getUsers().subscribe(users => {
        this.data = users;
    },
    error => { this.errorMessage = <any>error },
    () => {
        //Complete
        this.changeDetectorRef.detectChanges();
        const table: any = $("#user-table").DataTable();
        this.dataTable = table.DataTable();
    });
    

回答by jayesh wasnik

The problem happens because the table gets rendered before you get your data.

出现问题是因为表格在您获取数据之前已呈现。

Although it is not a proper solution but adding a timeout solves this.

虽然这不是一个合适的解决方案,但添加超时可以解决这个问题。

To your datatableadd this *ngIf="showContent":

为了您的数据表中添加本 *ngIf="showContent"

  <table datatable="ng" *ngIf="showContent" [dtOptions]="dtOptions" class="row-border hover table-bordered">

and then in your component .ts file add this to ngOnInit()

然后在您的组件 .ts 文件中将其添加到 ngOnInit()

setTimeout(()=>this.showContent=true, 250);

also declare the dummy variable showContent.

还要声明虚拟变量showContent

Hope it helped.

希望它有所帮助。

回答by Kihats

According to the documentation here, add the following cssto your styles.css

根据此处的文档,将以下内容添加css到您的styles.css

/*
server-side-angular-way.component.css
 */
.no-data-available {
  text-align: center;
}

/*
   src/styles.css (i.e. your global style)
*/
.dataTables_empty {
  display: none;
}

This will not show 'No Data' when you have data.

当您有数据时,这不会显示“无数据”。