【发布时间】: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