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

时间:2017-01-24 12:12:15

标签: javascript angularjs

  1. 我想使用$ http只为我的服务而不是控制器,我可以吗?
  2. 所以,当我尝试在$ scope中显示我的数据时,我的console.log上没有定义。
  3. 这里是我的代码

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

2 个答案:

答案 0 :(得分:0)

您必须返回承诺并等待该承诺完成。

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

答案 1 :(得分:0)

它返回一个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;
        });
    }
}]);