Http状态代码工厂AngularJs

时间:2016-05-02 17:57:10

标签: javascript angularjs json

我是使用AngularJs的新手,我使用$ http get创建了一个简单的工厂,它获得了一个.json,它有一堆或http状态代码作为键,以及它们各自的消息作为值。由于某种原因,我想得到这个错误:

无法读取未定义的属性'get'

JSON:

{
    "200": "Ok",
    "201": "Created",
    "202": "Accepted",
    "404": "Not_Found",
    "400": "Bad Request",
    "403": "Forbidden",
    "417": "Expectation Failed"
}

factory.js

  .factory('statusCodesFactory', function () {

                var httpStatusCodes = {
                    getStatus: function ($http) {
                        $http.get('catalog/statusCodes.json')
                            .then(function (response) {
                               httpStatusCodes.code = response;
                            });
                    }
                }
                return httpStatusCodes;
            })

3 个答案:

答案 0 :(得分:5)

你需要传递' $ http'正常。

.factory('statusCodesFactory', ['$http', function ($http) {
    var httpStatusCodes = {
        getStatus: function () {
            $http.get('catalog/statusCodes.json')
                .then(function (response) {
                    httpStatusCodes.code = response;
                });
            }
        }
        return httpStatusCodes;
    });

这就是说,你的功能并没有真正归还任何东西。更好的格式是:

.factory('statusCodesFactory', ['$http', function ($http) {
    var httpStatusCodes = {
        getStatus: function () {
            return $http.get('catalog/statusCodes.json')
                .then(function (response) {
                    return response;
                });
            }
        }
        return httpStatusCodes;
    });

这样称呼:

var statusCodes = {};
statusCodesFactory.getStatus().then(function(response){
    statusCodes = response;
});

答案 1 :(得分:1)

向您的工厂注入$ http服务。

.factory('statusCodesFactory', ['$http', function ($http) {
    return {
        getStatus: function () {
           $http.get('catalog/statusCodes.json')
                .success(function (response) {
                    // 
                });
            }
        }
    };
}]);

调用函数 -

statusCodesFactory.getStatus();

如果需要将响应返回给控制器,则使用Promises。注入$ q服务 -

.factory('statusCodesFactory', ['$http', '$q', function ($http, $q) {
    return {
        getStatus: function () {
           var defer = $q.defer();
           $http.get('catalog/statusCodes.json')
                .success(function (response) {
                    defer.resolve(response);
                });
            }
           return defer.promise;
        }
    };
}]);

然后从控制器调用工厂方法为 -

statusCodesFactory.getStatus().then(function(response){
    // Use response
});

答案 2 :(得分:0)

该错误表示您无法在get上调用方法$http,因为$httpundefined。传递给$http的{​​{1}}参数是此问题的根源。你需要弄清楚传递给该函数的内容,以及为什么它是一个空对象。