2017-10-21 18 views
0

我从后端获取数据并以表格行的形式绑定到视图中,然后我在表上调用数据表函数,但函数在视图显示行。Angular 4 - Datatables在数据填充前被调用

import { Component, OnInit } from '@angular/core'; 
import {HttpClient} from '@angular/common/http'; 
declare var $ :any; 

@Component({ 
    selector: 'app-vendors', 
    templateUrl: './vendors.component.html', 
    styleUrls: ['./vendors.component.css'] 
}) 
export class VendorsComponent implements OnInit { 

    vendors: any; 
    constructor(private http: HttpClient) { } 

    ngOnInit() { 

    this.http.get('backendgetLINK').subscribe(data => { 
     // Read the result field from the JSON response. 
     this.vendors = data['vendors']; 
     $("#vendors-datatable").DataTable({}); 

     console.log(this.vendors); 
    }); 
    } 

} 

回答

0

实测值的溶液

import { Component, OnInit } from '@angular/core'; 
import {HttpClient} from '@angular/common/http'; 
declare var $ :any; 

@Component({ 
    selector: 'app-vendors', 
    templateUrl: './vendors.component.html', 
    styleUrls: ['./vendors.component.css'] 
}) 
export class VendorsComponent implements OnInit { 

    vendors: any; 
    dataRetrieved:any; 
    constructor(private http: HttpClient) { 
this.dataRetrieved=false; 
    } 

    ngOnInit() { 

    this.http.get('backendLINK').subscribe(data => { 
     // Read the result field from the JSON response. 
     this.vendors = data['vendors']; 
     this.dataRetrieved=true; 
     // $("#vendors-datatable").DataTable({}); 

     console.log(this.vendors); 
    }); 
    } 
    ngAfterViewChecked() { 
    if (this.dataRetrieved) { 
    $("#vendors-datatable").DataTable({}); 
    } 
} 

} 

这是适当的一个?

0

生命周期钩子ngAfterViewInit将在组件视图及其子视图初始化后调用。

试试这个

ngAfterViewInit(){ 
    $("#vendors-datatable").DataTable({}); 
} 
+0

不能正常工作,不得不做出一个标志,检查从http – JenuRudan

+0

获取数据需要一定的时间,可能是'.http.get()'有一定的回调这样'.http。 get()。then()'。请检查我不确定的文档 – Hareesh