jquery - Angular - 数据表 : TypeError: Cannot read property 'nodeName' of null

标签 jquery angular typescript datatables

这个很棘手,我会尽力解释自己。

简要说明:

我在我的 Angular 项目中集成了 DataTables 库,几个月前我购买了该项目的主题。主题已更新,因此我继续使用最新版本更新我的项目。

奇怪的是,不起作用的是DataTables,而且DataTables没有被改变!

代码分解:

我正在从 X 组件触发我的共享服务 IBOsService 的一个方法。

当触发此方法时,我的 DatatableComponent 会在 Promise 中导入数据表库。

从来没有遇到过这方面的问题,直到现在。

DatatableComponent中:

this.tablesService.initTableData$.subscribe(() => {
                if (!this.datatableInitialized) {
                    log.info('Starting script import promise');

                    Promise.all([
                        System.import('script-loader!my-plugins/datatables-bundle/datatables.min.js')
                    ]).then(values => {
                        log.data('success', JSON.stringify(values));
                        this.render();
                    }, reason => {
                        log.error('error', JSON.stringify(reason));
                    });
                }
            }
        );

在我的控制台中,我看到:DataTables 成功 [{}]。因此,我明白 promise 是成功的。

然后我们进入this.render();方法。

该方法一直持续到此处的这一行:

const _dataTable = element.DataTable(options);

问题是,在我的 IDE 中,我可以导航到所有变量、方法等...但我无法导航到 DataTable(),因此我猜只是无法识别此方法,这就是它抛出错误的原因。

但是,由于脚本是在promise中加载的,IDE没有DataTables方法的映射是正常的......

完整组件代码:

import { Component, Input, ElementRef, AfterContentInit, OnInit, Injectable, OnDestroy } from '@angular/core';
import { IBOsService } from '../../../+ibos/ibos.service';
import { Subscription } from 'rxjs/Subscription';
import { Log, Level } from 'ng2-logger';
import { logConfig } from '../../../../environments/log_config';

const log = Log.create('DataTables');
log.color = logConfig.dataTable;

declare let $: any;

@Component({

    selector: 'sa-datatable',
    template: `
        <table class="dataTable {{tableClass}}" width="{{width}}">
            <ng-content></ng-content>
        </table>
    `,
    styles: [
        require('my-plugins/datatables-bundle/datatables.min.css')
    ]
})
@Injectable()
export class DatatableComponent implements OnInit, OnDestroy {

    @Input() public options: any;
    @Input() public filter: any;
    @Input() public detailsFormat: any;

    @Input() public paginationLength: boolean;
    @Input() public columnsHide: boolean;
    @Input() public tableClass: string;
    @Input() public width = '100%';

    public datatableInitialized: boolean;

    public subscription: Subscription;

    constructor(private el: ElementRef, private tablesService: IBOsService) {
        this.tablesService.refreshTable$.subscribe((tableParams) => {
                this.filterData(tableParams);
            }
        );

        this.tablesService.initTableData$.subscribe(() => {
                if (!this.datatableInitialized) {
                    log.info('Starting script import promise');

                    Promise.all([
                        System.import('script-loader!my-plugins/datatables-bundle/datatables.min.js')
                    ]).then(values => {
                        log.data('success', JSON.stringify(values));
                        this.render();
                    }, reason => {
                        log.error('error', JSON.stringify(reason));
                    });
                }
            }
        );
    }

    ngOnInit() {
    }

    render() {
        log.info('Starting render!');

        const element = $(this.el.nativeElement.children[0]);
        let options = this.options || {};

        log.info('1 render!');

        let toolbar = '';
        if (options.buttons) {
            toolbar += 'B';
        }
        log.info('2 render!');

        if (this.paginationLength) {
            toolbar += 'l';
        }

        if (this.columnsHide) {
            toolbar += 'C';
        }

        log.info('3 render!');

        if (typeof options.ajax === 'string') {
            const url = options.ajax;
            options.ajax = {
                url: url,
                // complete: function (xhr) {
                //
                // }
            };
        }

        log.info('4 render!');

        options = $.extend(options, {

            'dom': '<\'dt-toolbar\'<\'col-xs-12 col-sm-6\'f><\'col-sm-6 col-xs-12 hidden-xs text-right\'' + toolbar + '>r>' +
            't' +
            '<\'dt-toolbar-footer\'<\'col-sm-6 col-xs-12 hidden-xs\'i><\'col-xs-12 col-sm-6\'p>>',
            oLanguage: {
                'sSearch': `<span class='input-group-addon'><i class='glyphicon glyphicon-search'></i></span>`,
                'sLengthMenu': '_MENU_'
            },
            'autoWidth': false,
            retrieve: true,
            responsive: true,
            initComplete: (settings, json) => {
                element.parent()
                    .find('.input-sm')
                    .removeClass('input-sm')
                    .addClass('input-md');
            }
        });

        log.info('5 render! element', JSON.stringify(element));
        log.info('5.1 render! options', JSON.stringify(options));

        const _dataTable = element.DataTable(options);

        log.info('5.2 render! _dataTable', JSON.stringify(_dataTable));

        if (this.filter) {
            // Apply the filter
            element.on('keyup change', 'thead th input[type=text]', function () {
                console.log('searching?');
                _dataTable
                    .column($(this).parent().index() + ':visible')
                    .search(this.value)
                    .draw();
            });
        }

        log.info('6 render!');

        if (!toolbar) {
            element.parent().find('.dt-toolbar')
                .append(
                    '<div class="text-right">' +
                    '<img src="assets/img/logo.png" alt="SmartAdmin" style="width: 111px; margin-top: 3px; margin-right: 10px;">' +
                    '</div>'
                );
        }

        log.info('7 render!');

        if (this.detailsFormat) {
            const format = this.detailsFormat;
            element.on('click', 'td.details-control', function () {
                const tr = $(this).closest('tr');
                const row = _dataTable.row(tr);
                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    row.child(format(row.data())).show();
                    tr.addClass('shown');
                }
            });
        }

        log.info('8 render!');

        this.datatableInitialized = true;
    }

    filterData(tableParams) {
        console.log('reloading DT... With these parameters: ' + JSON.stringify(tableParams));

        const element = $(this.el.nativeElement.children[0]);
        const table = element.find('table.dataTable');

        log.data('current table element is: ', JSON.stringify(table));

        Object.keys(tableParams).forEach(function (key) {
            log.warn('current key: ', JSON.stringify(key));
            table.DataTable().column(`${key}:name`).visible(tableParams[key]);
        });

        table.DataTable().ajax.reload();
    }

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}

您会看到我已经使用日志侵入组件,它帮助我了解我的组件出现故障的位置。

完整控制台日志:

enter image description here

有趣的信息:

如果我调用 filterData(tableParams) 方法... DataTable 呈现没有问题。

这告诉我两件事:

  1. DataTable() 不是问题。
  2. 问题仅在第一次渲染时出现,然后在更新时,我没有遇到任何问题。

我为我的文字墙感到非常抱歉......但我自己做了一些夏洛克福尔摩斯,但找不到解决方案。

如果您需要澄清或更多详细信息,请告诉我。

提前致谢!

更新:

经过几天的调试,我发现了一个可能的错误来源:

enter image description here

问题是 snull

也许对 DataTables 更有经验的人或遇到这个问题的人可以给我一些提示,告诉我发生了什么。

我会在这里调试...;)

更新 2:

经过更多调试后,我发现 DataTables 没有进行第一个 Ajax 调用

我正在使用服务器端数据表,在 POST 中使用 Ajax 调用。

这是我的 options 对象的代码:

this.options = {
    dom: 'Bfrtip',
    processing: true,
    serverSide: true,
    pageLength: 20,
    searchDelay: 1200,
    ajax: {
        url: this.jsonApiService.buildURL('/test_getUsers.php', 'remote'),
        type: 'POST',
        data: function (d) {
            Object.assign(d, IBOsTable.params);
            log.data('DT options obj. New params are: ', JSON.stringify(IBOsTable.params));
            return d;
        }
    },
    columns: this.initColumns,
};

不是在初始化时进行 Ajax 调用,而是在 table.DataTable().ajax.reload(); 上进行。

这告诉我代码没有错误或损坏(在 reload() 上工作就像一个魅力)...

我仍然没有完全理解为什么这个 DataTables 的初始化不起作用......但我相信我已经足够接近了!

最佳答案

终于找到错误的根源了!

如果您阅读我的更新,您会发现我发现我的 DataTables 不是在进行第一个 Ajax 调用,而是在 reload() 上工作完美:

那是因为初始化中的 JavaScript 错误不允许进行 Ajax 调用。提示:类型错误:无法读取 null 的属性“nodeName”

speaking to Allan (from DataTables) 之后,他给了我提示,错误可能是由于 thead 的列数引起的。不等于 tbody 的列数.

所以我检查了我的 .html,发现我有一些空的 <thead><tfoot>标签。我评论了他们...并且成功了!

enter image description here

我已经遍历了所有可能的解决方案:

  • 依赖
  • Angular 2 应用程序中的 jQuery 库
  • 实例化 DataTable 服务器端的多种不同方式
  • 改变代码中的方法:TypeScript、jQuery、Ng2 等...

最后我只需要清除我的 DataTable 被加载到的 div 以避免这个问题。

有趣的事实:有了那个 .html,我的应用程序可以正常运行 3/4 个月,直到现在 DataTables 也没有问题...

关于jquery - Angular - 数据表 : TypeError: Cannot read property 'nodeName' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44586587/

相关文章:

jquery - 与 Foundation 一起启动新的 Rails 项目

javascript - 视口(viewport) JQuery - 如果元素在视口(viewport)中,则将文档准备好

typescript - 在 typescript 中打字

typescript - 可调用的 typescript 接口(interface)不可调用?

javascript - 如何将 NgbDate 转换为 js Date 对象?

javascript - 从 ASP.NET Web API 方法向 jquery ajax 发送间歇性响应

即使 cors = true,Jquery ajax 也无法在 IE9 中工作

javascript - 移动网络应用程序上的 keyup 似乎仍然没有覆盖内容 block

angular - 如何向守卫传递参数?

css - 着陆页的 Angular 条件 CSS