首页 > 解决方案 > Angular2 - 使用订阅的 Angular 数据表

问题描述

我正在尝试将Angular数据表与 angular2 一起使用。代码与此类似

myArray: any;

function test() {
    callService subscribe((response) => {
        this.myArray = response['body'];
    })
    this.datatableOptions();
}

datatableOptions() {
    this.dtOptions = {
        order: [1, "desc"],
        pagingType: "full_numbers",
        pageLength: 100,
        lengthMenu: [
            [100, 150, 200, -1],
            [100, 150, 200, "Todo"]
        ],
        responsive: true,
        rowCallback: function(row, data, index) {
            var api = this.api();
            $('td:eq(0)', row).html(index + (api.page() * api.page.len() + 1));
        },
        processing: true,
        searching: true,
        deferRender: true,
        data: JSON.parse(JSON.stringify(this.myArray)),
        columns: [{
                targets: 0,
                data: null
            },
            {
                targets: 1,
                data: 'A',
                defaultContent: '-'
            },
            {
                targets: 2,
                data: 'B',
                defaultContent: '-'
            },
            {
                targets: 3,
                data: 'C',
                defaultContent: '-'
            },
        ],
    }
}

问题:console.log(response['body'])有数据,但数据表没有显示任何数据。那么,这段代码有什么问题?

标签: angulardatatable

解决方案


该函数可能不知道“ this ”。在订阅函数中,“this”是函数的作用域,而不是组件。

你可以用这个技巧来避免它:


myArray: any;

function test() {
    let thisContext = this;
    callService subscribe((response) => {
        thisContext.myArray = response['body'];
    })
    this.datatableOptions();
}

因此,当您将测试函数输入到 thisContext 变量时,您将“this”范围绑定。在 subscribe 函数中,您使用 thisContext 变量引用该范围。

这样,您应该会找到填充了数据的 myArray 变量。


推荐阅读