簡體   English   中英

如何使用$ http響應控制器獲取服務功能

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

  1. 我只想為服務而不是控制器使用$ http,可以嗎?
  2. 因此,當我嘗試在$ scope中顯示數據以查看時,我在console.log上未定義。

這是我的代碼

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM