ES6 Angular-Meteor ng-table's getData function is not being invoked

I've been working on updating my code to ES6. Specifically, I'm using angular-meteor and ng-table. Everything was displaying correctly in the table before the refactor, but now after converting to ES6 syntax, the data no longer appears. Here is a portion of the new code:

class MyController {
    constructor($scope, $reactive, NgTableParams, MyService) {
        'ngInject';

        $reactive(this).attach($scope);

        this.subscribe('myCollection');

        this.myService = MyService;

        this.helpers({
            items() {
                return this.myService.getItems();
            },
            itemTableParams() {
                const data = this.getReactively('items');

                return new NgTableParams({
                    page: 1,
                    count: 10
                }, {
                    total: data.length,
                    getData: (params) => {
                        // not called
                    }
                });
            }
        });
    }
}

class MyService {
    getItems() {
        return MyCollection.find({}, {
            sort: {
                dateCreated: -1
            }
        });
    }
}

export default angular.module('MyModule', [angularMeteor, ngTable, MyService])
    .component('MyComponent', {
        myTemplate,
        controllerAs: 'ctrl',
        controller: MyController
    })
    .service('MyService', MyService);

The const data variable gets populated, however, the getData function isn't being triggered. The table in the template is utilizing ctrl.itemTableParams for the value of the ng-table attribute, with item in $data for the ng-repeat.

Any insights into why the getData function isn't executing? Your help would be greatly appreciated. Thank you!

P.S. I've noticed that if I set NgTableParams to a const tableParams, and then call the reload() function, the getData function does get triggered. However, the data still doesn't appear on the table. This is how I'm setting up the table:

itemTableParams() {
    const data = this.getReactively('items');
    const tableParams = new NgTableParams({
        page: 1,
        count: 10
    }, {
        total: data.length,
        getData: (params) => {

        }
    });

    tableParams.reload(); // triggers the getData function
    return tableParams;
}


<table ng-table="ctrl.itemTableParams">
    <tr ng-repeat="item in $data track by $index">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.dateCreated}}</td>
    </tr>
</table>

Even though I see items in the getData log, the data is still not rendering in the table.

Answer №1

It seems that the solution lies in simply returning the data within the getData function. The previous documentation was using $defer.resolve without properly returning the resolved data. In the updated version (1.0.0), this is no longer necessary.

this.helpers({
  items() {
    return this.myService.getItems();
  },
  itemTableParams() {
    const itemsData = this.getReactively('items');

    return new NgTableParams({
      page: 1,
      count: 10
    }, {
      total: itemsData.length,
      getData: (params) => {
        const filteredData = filterData(itemsData); // perform some operations

        return filteredData;
      }
    });
  }
});

Answer №2

The issue with the current code is that the getData method is not being triggered due to the asynchronous nature of fetching the data. This results in calling getData with unresolved data when the controller is initially loaded.

To resolve this issue, you should instantiate the NgTableParams within the success callback of the data object:

data.$promise.then((data) => {
 // instantiate NgTableParams here
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Processing data from a Buffer object using the .map() method and sending it as props to a component

As I work on my application, I encounter a challenge when dealing with a Buffer object that contains data from a file. My intention is to render the component Bar for each byte in this buffer and pass the byte as a prop. However, I am facing an issue with ...

GraphQL Shield throws an 'Unauthorized' error for a permitted mutation

I've been working on setting up a GraphQL API with apollo-server-express, and I'm trying to handle permissions using graphql-shield middleware. However, I'm running into some issues when it comes to allowing mutations to be executed. My aim ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

Does it typically occur to experience a brief pause following the execution of .innerHTML = xmlhttp.responseText;?

Is it common to experience a brief delay after setting the innerHTML with xmlhttp.responseText? Approximately 1 second delay occurs after xmlhttp.readyState reaches 4. This issue is observed when using Firefox 3.0.10. ...

What is the best way to link options from a select directive with a different array?

Update: the working jsfiddle can be found here: http://jsfiddle.net/robertyoung/jwTU2/9/ I'm in the process of developing a webpage/app using AngularJS. The specific functionality I aim to achieve involves allowing users to add a row to the timecard ...

Validating JSON against a JSON schema using JavaScript

My current task involves validating approximately 100 JSON Objects against a specific JSON schema to ensure that all fields and their types align with the schema requirements. Initially, I attempted to use a JSON schema generated from a website. However, ...

CSS: Hover below the designated target to reveal an expanding dropdown menu

My initial solution involved toggling the visibility on and off when hovering. However, this approach is not optimal as the menu should smoothly transition into view. When the visibility is toggled, the user does not experience the intended transition effe ...

The issue with the autoresize feature in the tinymce plugin arises when trying to delete HTML img content using the backspace

When using the tinymce editor with the autoresize plugin enabled, I have noticed that it works correctly with text. However, there is an issue when inserting HTML content via execCommand. For example, if I insert the following code: <div> < ...

Button react-native press following textInput within scroll view aware of keyboard movements

I'm currently facing an issue where I have a TextInput and a button nested inside a KeyboardAwareScrollView. The goal is for the user to input some text and then tap the button created using TouchableOpacity, which should send the inputted text forwar ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

The input-group-btn is positioned to the right of the field, appearing to float

The input-group-btn for the targetDate field remains fixed on the right side of the input group despite screen width variations until I introduce the automatically generated CSS from the hottowel generator. I require assistance in identifying which aspect ...

I am working with Vue.js 2.0 and attempting to send an event from a `child component`

I've been working with Vue.js 2.0 and I'm facing an issue trying to emit an event from a child component to the parent component, but unfortunately, it's not functioning as expected. Here is a glimpse of my code: child component: <temp ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

CSS animations for loading page content

Currently, I am incorporating animations into my project using HTML5 and CSS3, and the progress has been smooth. I have been able to achieve effects such as: #someDivId { position: absolute; background:rgba(255,0,0,0.75); transition: all 0.7s ...

Unable to extract a particular value from a JSON data structure

This situation has been on my mind for a good couple of hours now. I have this json object with example values like so: { "events": [ { "id": 64714, "live": false, "start": "1399117500", "league_ ...

The event.target.x attribute on the <i /> tag element

In my code, there is an <i name="documentId" onClick={this.openDocument}/> element with the onClick method defined as follows: openDocument(event) { const { name } = event.target; console.log('name', name); console.log('target&a ...

The initial setting of [opened]="true" causes an issue with the Angular Material date range picker

Recently, we completed the upgrade of our app from Angular 14 to 15.2.9, which includes Angular Material. The migration process went smoothly, and now our app is compiling and running without any errors. However, we encountered an issue with the mat-date-r ...

Assigning binary messages a structure similar to JSON for the purpose of easy identification

Is there a way to differentiate binary messages from a server by tagging them with a type attribute? Currently, I am working with node.js and sending binary images as blobs to my client. However, I now also need to send other file types like .txt over the ...

Deciphering the Cause of mapStateToPropsCall in Redux and React

When handling an unsuccessful http call resulting in an error message being displayed, I encounter subsequent state changes triggering multiple render calls. Is there a technique to identify the cause of these state changes and mapStateToProps calls? Alter ...