根据 AngularJS,我的 $http
通过我的 Controller 的服务调用返回未定义?
这似乎是什么问题?我正在尝试返回调用的数据,但是一旦传递给 Controller ,数据就变成未定义的了吗?
JavaScript
var myStore = angular.module('myStore', [])
.controller('StoreController', ['$scope', 'dataService', function ($scope, dataService) {
$scope.products = dataService.getData();
}])
.service('dataService', ['$http', function($http) {
this.getData = function() {
$http.get('assets/scripts/data/products.json')
.then(function(data) {
return data;
});
};
}]);
HTML
<div class="content">
<ul>
<li ng-repeat="product in products.products">{{product.productName}}</li>
</ul>
</div>
我知道 $http
、$q
和 $resource
都是返回 promise ,但我想我已经用 .then 覆盖了它.
最佳答案
问题可能是您没有在 dataService.getData
函数中返回
由 $http.get
创建的 promise 。换句话说,您可以通过更改您所拥有的内容来解决您的 undefined
问题:
.service('dataService', ['$http', function($http) {
this.getData = function() {
return $http.get...
};
}
如果您在 dataService.getData
中对 $http.get
进行了多次调用,下面是您可能如何处理它们。
.service('dataService', ['$http', function($http) {
this.getData = function() {
var combinedData, promise;
combinedData = {};
promise = $http.get(<resource1>);
promise.then(function (data1) {
combinedData['resource1Response'] = data1;
return $http.get(<resource2>);
});
return promise.then(function (data2) {
combinedData['resource2Response'] = data2;
return combinedData;
});
};
}]);
但是,更简洁的方法是使用 $q.all
.service('dataService', ['$http', '$q', function($http, $q) {
this.getData = function() {
var combinedData, promises;
combinedData = {};
promises = $q.all([
$http.get(<resource1>),
$http.get(<resource2>)
]);
return promises.then(function (allData) {
console.log('resource1 response', allData[0]);
console.log('resource2 response', allData[1]);
return allData;
});
};
}]);
关于javascript - AngularJS $http 返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29738684/