简体   繁体   English

如何使用$ http响应控制器获取服务功能

[英]how to get service function with $http response to controller

  1. i want use $http just for my service not controller, can i? 我只想为服务而不是控制器使用$ http,可以吗?
  2. so, i got undefined on my console.log when i try to showing my data in a $scope to view. 因此,当我尝试在$ scope中显示数据以查看时,我在console.log上未定义。

here my code 这是我的代码

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;
            });
    }
}]);

You have to return a promise and wait for that promise to be fullfilled. 您必须返回一个承诺并等待该承诺被兑现。

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

It returns a promise, and the data should be set after the promise is resolved: 它返回一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM