Http状态代码工厂AngularJs

Http Status Code Factory AngularJs

本文关键字:AngularJs 工厂 代码 状态 Http      更新时间:2023-09-26

我是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;
            })

您需要正确地传递'$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;
});

向工厂注入$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
});

错误表示不能在$http上调用方法get,因为$httpundefined。传递给getStatus: function($http)...$http参数是这个问题的根源。您需要弄清楚传递给该函数的是什么,以及为什么是空对象。