首页 文章

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

提问于
浏览
3

当我试图在角度js中显示数据表时 . 它显示表中没有可用数据,但表中有4条记录 . 见下面的截图 .

enter image description here

这就是我做的 .

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 看起来像这样

[
 {"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的新手来说非常有帮助 .

4 回答

  • 0

    添加了超时以解决您的问题 .

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

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

  • 1

    user.component.ts 中,将数据var声明为空以初始化它 . 我没有'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'工作 .

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

    我错了

    你必须重新渲染数据表,因为如果你重新渲染初始化会抛出一个错误,这就是为什么你有消息说“没有数据可用”,尽管你已经在表中 .

    UPDATE

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

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

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

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

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

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

    在组件中使用此库:

    import { DataTableDirective } from 'angular-datatables';
    

    在您的应用模块中:

    import { DataTablesModule } from 'angular-datatables';
    

    并宣布:

    imports: [
               ...,
               DataTablesModule
    

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

    希望有所帮助

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

  • 2

    使用超时功能是一种不好的做法 . 当您使用角度时,解决此问题的最佳方法是使用 change detection .

    首先通过在构造函数中添加它来创建此实例,如下所示,

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

    现在使用 detectChanges 函数,以便角度等待直到某些内容发生变化(在您的情况下,直到表格生成正确)

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

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

  • 0
    • 在构造函数上添加此代码:
    private changeDetectorRef: ChangeDetectorRef
    
    • 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();
    });
    

相关问题