【问题标题】:MVC and Angularjs : promise does not waiting dataMVC 和 Angularjs:承诺不等待数据
【发布时间】:2016-04-20 08:56:13
【问题描述】:

我是 angularjs 的新手,我在互联网上进行了研究,但我找不到任何适合我的问题的解决方案。我进行了 http 调用以从控制器获取一些数据。控制器端没问题。但是在客户端,promise 不会等待数据。这是我写的代码;

//service code 
angular.module("myApp").service('$myService', function ($http, $q) {
            this.getDataArray = function () {
                var deferred = $q.defer();
                $http.get('../Home/GetDataArray')
                    .success(function success(response) {
                        deferred.resolve(response);
                    })
                    .error(function () {
                        console.log("error getting data array");
                        deferred.reject();
                    });

                return deferred.promise;
            };
    }

// controller-code
angular.module("myApp").controller('dataController', function ($scope, $http, $myService) {

        $scope.getDataFromService = function () {
            $myService.getDataArray().then(function (response) {
                    $scope.dataArray = response.data;
                });
        };
    });
}

当我第一次调用 getDataFromService 方法时,$scope.dataArray 是空的,但第二次调用时,$scope.dataArray 会填充数据。哪里有问题?感谢您的帮助。

【问题讨论】:

  • 你能在 fiddler/chrome 开发工具中检查第一次 HTTP 调用的结果吗?
  • 我也检查过了,但是当我第一次调用时,$scope.dataArray 是空的,因为 promise 不会像我说的那样等待
  • 我不是指 $scope.data,我指的是 HTTP 调用本身。您确定第一次调用的响应(如 Chrome 开发工具中所示)包含数据吗?
  • 不,第一次调用不包含数据。
  • 好吧,如果第一次调用不包含数据,那么问题出在服务器上

标签: angularjs asynchronous promise angular-promise


【解决方案1】:

我自己不是角度专家。当我遇到同样的问题时,我就是这样做的。试试这个:

控制器:

angular.module("myApp").controller('dataController',[ '$scope', 'Service1', '$http', function ($scope, Service1, $http) {
    var deferred = Service1.getDataArray().$promise;
            return deferred.then(function successCallback(data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                $scope.dataArray = response.data;
            }, function errorCallback(response) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            })
    }])

和服务:

   var service = angular.module("myApp").service('myService', ['ngResource']);
  myService.factory('Service1', ['$resource',
  function ($resource) {
      return $resource('../Home/GetDataArray', {}, {
          get: { method: 'GET', isArray: true },
      });
  }])

我们的想法是,您的服务不是应该等待返回的服务,而是您的控制器。所以你应该在你的控制器而不是你的服务中等待承诺。在我的示例中,我使用了工厂,因为这就是我在项目中解决它的方式,如果您不想使用工厂,可以尝试直接实现它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2019-04-29
    • 2018-02-03
    • 2014-06-14
    • 2019-12-10
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多