【问题标题】:how to await data from meteor call?如何等待来自流星呼叫的数据?
【发布时间】:2019-10-12 07:26:15
【问题描述】:

我是angular1.5的初学者,我的问题是Meteor.call()返回的数据不显示在HTML中

这是我的代码:

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]);

数据在这里不起作用:

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>

我希望 html 中的输出与从 getData 函数返回的 HubsController 类中的输出相同

【问题讨论】:

    标签: angularjs meteor angular-meteor


    【解决方案1】:

    一种方法是从基于回调的 API 创建一个 AngularJS 承诺:

    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;
    }
    

    当 AngularJS 承诺解决时,AngularJS 框架会自动调用 $apply。这会将数据带入 AngularJS 执行上下文。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等。

    【讨论】:

      【解决方案2】:

      我解决了。 我错过了绑定数据的$apply() 方法。

        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;
            });
          });
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-29
        • 1970-01-01
        • 2018-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 2018-04-27
        相关资源
        最近更新 更多