MVC 和 Angularjs :promise 不等待数据

MVC and Angularjs : promise does not waiting data

我是 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 填充了数据。问题出在哪里?感谢您的帮助。

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

控制器:

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

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