使用AngularJS服务无法获取数据

时间:2015-03-30 17:37:22

标签: javascript angularjs

如果我访问链接http://localhost/cgi-bin/superCategory.pl?action=GET 我会得到这些数据:

[{"name":"Baby Care","id":"2","image":"/images/categories/baby-care.png"},{"name":" Bread, Bakery & Dairy Products","id":"5","image":"/images/categories/dairy-products.png"},{"name":"Beverages","id":"6","image":"/images/categories/beverages.png"},{"name":"Others","id":"9","image":"/images/categories/others.png"}]

但是当我尝试使用AngularJS服务和控制器获取相同的数据时,我得不到数据。这是我的控制器和服务代码。

sampleApp.factory('SuperCategoryService', ['$http', function ($http){
  var req = {
    method: 'POST',
    url: 'http://localhost/cgi-bin/superCategory.pl',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    data: { action: 'GET' }
};  

  return {
        GetSuperCategories: function () {
            return $http(req).then(

                function(response) 
                {
                    if (typeof response === 'object') 
                    {
                        return response;
                    } 
                    else 
                    {
                        alert ('wrong');
                    }
                },
                function(response) {
                    alert ('again worng');
                    // something went wrong
                    //return $q.reject(response.data);
                });
            }
        };
}]);

sampleApp.controller('SuperCategoryController', function ($scope,SuperCategoryService) {

    $scope.SuperCategories = [];

    $scope.GetSuperCategories = function() {

        SuperCategoryService.GetSuperCategories().then(
        function(d) {
            alert (d);
            if (d !== undefined) {
                alert ('in');
                console.log(d);
                $scope.SuperCategories = d;
            }
            else  {
                alert ('undefined data');
            }
        },

        function(response) {
            alert ('error worng');
            // something went wrong
            //return $q.reject(response.data);
        });

    };

    $scope.GetSuperCategories();
});

尽管代码已达到警报('in'),但没有任何内容被分配给变量$ scope.SuperCategories;

有人可以帮我解决分配错误的问题。

1 个答案:

答案 0 :(得分:1)

您的服务功能使用$http进行.then这只不过是使用链承诺解析您应该从服务对象获取显式数据,而不是response.data response

   GetSuperCategories: function () {
        return $http(req).then(

            function(response) 
            {
                var data = response.data;
                if (typeof data === 'object') 
                {
                    return data ;
                } 
                else 
                {
                    alert ('wrong');
                }
            },
            function(response) {
                alert ('again worng');
                // something went wrong
                //return $q.reject(response.data);
            });
        }
    };