简体   繁体   中英

Rename anonymous function's parameter name getting error Argument of type '' is not assignable to parameter of type ''

I would like to access the current page of data from angular-datatables, thus I am using DataTableDirective like below:

@ViewChild(DataTableDirective, { static: false }) dtElement: DataTableDirective;
dtData: {id: number, name: string, selected: boolean}[];

selectAll(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
        dtInstance.rows({ page: 'current' }).every(function() {
            const id = this.data()[0];
            // statement below not working as function override the `this` keyword
            // thus I can't refer to the dtData declared in global scope.
            const currentRow = this.dtData.find(item => item.id === id);
            currentRow.selected = true;
        });
    });
}

The function selectAll() will be triggered on button click, dtInstance.rows({ page: 'current' }).every() function will loop through each row of the datatable of current page.

I check the source code of the every() function, it has the following function signature:

    /**
     * Iterate over each selected row, with the function context set to be the row in question. Since: DataTables 1.10.6
     *
     * @param fn Function to execute for every row selected.
     */
    every(fn: (this: RowMethods, rowIdx: number, tableLoop: number, rowLoop: number) => void): Api;

As you can see, it declares the this as variable of RowMethods , that's why I am able to access the data with this.data() , but this create a problem where I can't refer to the global context of this inside this anonymous function, thus I would like to "rename" the variable name of this , I tried it with the code below:

dtInstance.rows({ page: 'current' }).every(function(a: DataTables.RowMethods, b: number, c: number, d: number) {
    console.log(a.data());
});

But getting error

Argument of type '(a: RowMethods, b: number, c: number, d: number) => void' is not assignable to parameter of type '(this: RowMethods, rowIdx: number, tableLoop: number, rowLoop: number) => void'.

May I know what I did wrong here? I suspec the problem is on the datatype RowMethods , somehow compiler treat DataTables.RowMethods differently with RowMethods , but I don't know what I can do with this. Any help or workaround would be appreciated!

Have you tried with the arrow function => to keep this in the global context?

dtInstance.rows({ page: 'current' }).every((a: DataTables.RowMethods, b: number, c: number, d: number) => {
    console.log(this);
    console.log(a.data());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM