Hossam Ali
Hossam Ali

Reputation: 49

how to await data from meteor call?

I'm so beginner in angular1.5, My problem is The data returned from Meteor.call() doesn't display in the HTML

Here's my code:

hubs.js

class HubsController {
  data = [];

  constructor($scope, $uibModal) {
    $scope.viewModel(this);

    this.$scope = $scope;
    this.$uibModal = $uibModal;

    this.initViews();

    this.subscribe('admin.verifiedBusinesses');
    this.subscribe('admin.verifiedStars');
    this.getData();
    console.log('data', this.data);
  }

  ...

  getData() {
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err);
      }
      // Initialize active routes.
      this.data = data;
      console.log(this.data); // data works fine
      return data;
    });
  }
}

angular
  .module('material-lite')
  .controller('hubsDataController', ['$scope', '$uibModal', HubsController]);

data don't work here:

hubs.html

<div class="table-responsive" style="overflow-x: hidden" ng-controller="hubsDataController">
  ...
            <tr ng-repeat="hubsData in data" class="table_row">
              <td>{{ hubsData.name }}</td>
              <td>

I expect the output in html is the same as in the HubsController class returned from getData function

Upvotes: 0

Views: 70

Answers (2)

georgeawg
georgeawg

Reputation: 48948

One approach is to create an AngularJS promise from the callback-based API:

getData() {
    const deferred = this.$q.defer();
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err);
        deferred.reject(err);
        return;
      }
      // Initialize active routes.
      this.data = data;
      console.log(this.data); // data works fine
      deferred.resolve(data);        
    });
    return deferred.promise;
}

When an AngularJS promise resolves, the AngularJS framework automatically invokes $apply. This brings the data into the AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.

Upvotes: 2

Hossam Ali
Hossam Ali

Reputation: 49

I solved it. I was missing the $apply() method to bind the data.

  getData() {
    Meteor.call('warehouse.getAll', (err, data) => {
      if (err) {
        console.log(err); // TODO
        swal('Error', err.reason, 'error');
        return;
      }
      // Initialize active routes.
      this.$scope.$apply(() => {
        this.$scope.data = data;
      });
    });
  }

Upvotes: 1

Related Questions