我有一个我想通过其获取数据的服务$http
(之所以这样,是因为我需要在我的应用中多次进行此调用)
服务运行良好,代码如下:
factory('websiteService', function($rootScope, $http) {
this.getWebsites = function(){
http({
method: 'GET',
url: './data/websites.json'
}).then(function successCallback(response) {
return response.data;
});
}
$rootScope.websiteService = this;
return this;
});
然后,我在几个控制器中使用它,如下所示:
.controller('MyCtrl', function($scope, websiteService) {
$scope.websites = websiteService.getWebsites(); // not working
});
不过,正如您所猜测的那样,这是行不通的。似乎websites
在$http
请求结束之前已定义,但是我可能是错的。
我该如何解决?
服务的定义方法如下:
myModule.factory('websiteService', function($http) {
function getWebsites() {
return $http({
method: 'GET',
url: './data/websites.json'
}).then(function successCallback(response) {
return response.data;
});
}
return {
getWebsites: getWebsites
};
});
这是应如何使用:
myModule.controller('MyCtrl', function($scope, websiteService) {
websiteService.getWebsites().then(function(webSites) {
$scope.webSites = webSites;
});
});
我建议您阅读有关AngularJS承诺的陷阱,反模式和技巧,以了解您对承诺所做的错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句