[英]Making angular HTTP call reusable
In my controller.js , I have an HTTP GET request that I have to call when my page loads and when a user pulls to refresh. 在controller.js中 ,我有一个HTTP GET请求,当页面加载以及用户拉动刷新时必须调用该请求。
The way I'm doing it right now is by duplicating the $http code. 我现在的操作方式是复制$ http代码。 Is there a way to make this more reusable?
有没有办法使它更可重用? I can't figure out how to move it to my services.js file and reference it in my controller so that it runs.
我不知道如何将其移动到我的services.js文件中,并在我的控制器中对其进行引用以使其运行。
.controller('GamesCtrl', function ($scope, $http) {
$http(
{
method: 'GET',
url: 'https://www.kimonolabs.com/api/dc6n4edu?apikey=U4SNiysE89aaLXSWRJgHKDZOByqSLM0p',
headers: {
'authorization': 'Bearer PW8V4OesZ61tCqSRNpXYtRn5ahcLdclU'
}
}).
success(function (data) {
$scope.data = data['results']['collection1'];
});
$scope.doRefresh = function() {
$http(
{
method: 'GET',
url: 'https://www.kimonolabs.com/api/dc6n4edu?apikey=U4SNiysE89aaLXSWRJgHKDZOByqSLM0p',
headers: {
'authorization': 'Bearer PW8V4OesZ61tCqSRNpXYtRn5ahcLdclU'
}
}).
success(function (data) {
$scope.data = data['results']['collection1'];
})
.finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
};
})
The simple answer is, make a private function: 简单的答案是,创建一个私有函数:
.controller('GamesCtrl', function ($scope, $http) {
var doLoad = function() {
$http(
{
method: 'GET',
url: 'https://www.kimonolabs.com/api/dc6n4edu?apikey=U4SNiysE89aaLXSWRJgHKDZOByqSLM0p',
headers: {
'authorization': 'Bearer PW8V4OesZ61tCqSRNpXYtRn5ahcLdclU'
}
}).
success(function (data) {
$scope.data = data['results']['collection1'];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});;
};
$scope.doRefresh = function() {
doLoad();
};
doLoad();
})
A more detailed answer might be to extract it into a service: 更详细的答案可能是将其提取到服务中:
.service('KimonoSvc',function($http) {
return {
get: function() {
return $http(
{
method: 'GET',
url: 'https://www.kimonolabs.com/api/dc6n4edu?apikey=U4SNiysE89aaLXSWRJgHKDZOByqSLM0p',
headers: {
'authorization': 'Bearer PW8V4OesZ61tCqSRNpXYtRn5ahcLdclU'
}
});
}
};
})
.controller('GamesCtrl', function ($scope, KimonoSvc) {
var doGet = function() {
KimonoSvc.get().
success(function (data) {
$scope.data = data['results']['collection1'];
}).finally(function() {
$scope.$broadcast('scroll.refreshComplete');
});
};
$scope.doRefresh = function() {
doGet();
};
doGet();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.