[英]How to make http call in service but get response by the controller? AngularJS
[英]how to get service function with $http response to controller
這是我的代碼
app.controller('adminControl', ['$scope','$routeParams','$route','adminService', function($scope,$routeParams,$route,adminService){
$scope.data = adminService.listOfAdmin();
console.log($scope.data);
}]).service('adminService', ['$http', function($http){
this.get = function(url){
return $http({
method:'GET',
url:url
}).then(function(response){
return response;
});
}
this.listOfAdmin = function(){
this.get('http://localhost/project/s9/ayu/admin/sys/mac.php?act=administrator')
.then(function(response){
return response.data;
});
}
}]);
您必須返回一個承諾並等待該承諾被兌現。
app.controller('adminControl', ['$scope','$routeParams','$route','adminService', function($scope,$routeParams,$route,adminService){
$scope.data = adminService.listOfAdmin().then(function(response) {
console.log(response.data);
});
}]).service('adminService', ['$http', function($http){
this.get = function(url){
return $http({
method:'GET',
url:url
});
}
this.listOfAdmin = function(){
return this.get('http://localhost/project/s9/ayu/admin/sys/mac.php?act=administrator');
}
}]);
它返回一個promise,並且應在promise解決后設置數據:
app.controller('adminControl', ['$scope','$routeParams','$route','adminService', function($scope,$routeParams,$route,adminService){
adminService.listOfAdmin().then(function(data) {
$scope.data = data;
console.log($scope.data);
});
}]).service('adminService', ['$http', function($http){
this.get = function(url){
return $http({
method:'GET',
url:url
}).then(function(response){
return response;
});
}
this.listOfAdmin = function(){
return this.get('http://localhost/project/s9/ayu/admin/sys/mac.php?act=administrator')
.then(function(response){
return response.data;
});
}
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.