gpt4 book ai didi

javascript - 使 Angular HTTP 调用可重用

转载 作者:行者123 更新时间:2023-11-28 19:27:25 26 4
gpt4 key购买 nike

在我的 controller.js 中,我有一个 HTTP GET 请求,当我的页面加载和用户拉取刷新时,我必须调用该请求。

我现在的做法是复制 $http 代码。有没有办法让它更可重用?我不知道如何将其移动到我的 services.js 文件并在我的 Controller 中引用它以便它运行。

.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');
});
};
})

最佳答案

简单的答案是,创建一个私有(private)函数:


.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();
})

更详细的答案可能是将其提取到服务中:


.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();
})

关于javascript - 使 Angular HTTP 调用可重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27582404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com