我从ngOnInit块中的webservice获取数据,然后我需要应用jquery数据表插件(此操作我在ngAfterViewInit和ngAfterContentInit中执行)。问题是jquery数据表插件没有看到在ngOnInit块中获取的组件表中的数据。我可以实现它的唯一方法是setTimeout或setInterval(如果创建了插件实例,则会停止执行)。
有没有其他方法可以执行我尝试的任务?
export class DataTable implements OnInit, AfterViewInit, AfterContentInit, AfterContentChecked {
public data = null;
public table = null;
constructor(public translate: TranslateService, public ngZone: NgZone) {
}
ngOnInit(): void {
this.translate.getData().subscribe((records) => {
this.data = records;
});
}
ngAfterViewInit(): void {
this.dataTableDynamicUpdater();
}
ngAfterContentInit() : void {
}
ngAfterContentChecked() {
}
dataTableDynamicUpdater() {
let self = this;
let interval = setInterval(() => {
if(self.data) {
self.instantiateDataTable();
clearInterval(interval);
}
}, 200);
}
instantiateDataTable() {
let _FILTER_PLACEHOLDER_ = this.translate.instant('APP_DATATABLE_PLACEHOLDER_TYPE_TO_FILTER');
let _FILTER_LABEL_ = this.translate.instant('APP_DATATABLE_LABEL_FILTER');
let _SHOW_LABEL_ = this.translate.instant('APP_DATATABLE_LABEL_SHOW');
$.extend($.fn.dataTable.defaults, {
autoWidth: false,
dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
language: {
search: '<span>_FILTER_LABEL_</span> _INPUT_',
lengthMenu: '<span>_SHOW_LABEL_</span> _MENU_',
paginate: { 'first': 'First', 'last': 'Last', 'next': '→', 'previous': '←' }
}
});
// Column selectors
let table = $('.table').DataTable({
buttons: {
buttons: [
{
extend: 'excelHtml5',
className: 'btn btn-default',
exportOptions: {
columns: ':visible'
}
}
]
}
});
// Add placeholder to the datatable filter option
$('.dataTables_filter input[type=search]').attr('placeholder', _FILTER_PLACEHOLDER_);
// Enable Select2 select for the length option
$('.dataTables_length select').select2({
minimumResultsForSearch: Infinity,
width: 'auto'
});
return table;
}
}
答案 0 :(得分:0)
在获取数据后尝试执行此操作
ngOnInit(): void {
let self = this;
this.translate.getData().subscribe((records) => {
this.data = records;
self.instantiateDataTable();
});
}