我有一个服务,我想通过 $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 中使用它,如下所示:
.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;
});
});
我建议你阅读 Traps, anti-patterns and tips about AngularJS promises了解您在 promise 方面所犯的错误。
关于angularjs - Angular - $scope 无法访问服务中的 $http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37632578/