Angular JS服务依赖注入错误

Angular JS service dependency injection error

我是 angular 的新手,我一直在尝试对用户名可用性进行异步验证,但我得到了 "Cannot read property 'userName' of undefined" 这是我的服务代码

webAppServices.factory('services', ['$resource',
function ($resource){
    return{
        users: $resource('http://localhost:8080/api/users',{},{
            get:{method:'GET',isArray:true},
            add:{method:'POST',isArray:false},
            update:{method:'POST',isArray:false}
        }),

       userName:$resource('http://localhost:8080/api/users/check/:username',{},{
            check:{method:'GET',isArray:false}
        })
    };}]);

这是我的指令代码,它通过用户名进行验证

webAppValidation.directive('checkUsername', ['services',
function ($q, services) {
    return {
        require: "ngModel",
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$asyncValidators.checkUsername = function(modelValue, viewValue){
               //check username
                return ctrl.$isEmpty(modelValue) || services.userName.check({username:modelValue}).
                        then(function resolved(){
                            //username exists, this means validation fails
                            return $q.reject('exists');
                        }, function rejected(){
                            //username does not exists, therefore this validation passes
                            return true;
                        });
            };
        }
    };
}]);

这就是我在控制台中得到的结果

TypeError: Cannot read property 'userName' of undefined
at link.ctrl.$asyncValidators.checkUsername (validations.js:56)
at angular.js:24723
at forEach (angular.js:350)
at processAsyncValidators (angular.js:24722)
at NgModelController.$$runValidators (angular.js:24681)
at NgModelController.$$parseAndValidate (angular.js:24819)
at NgModelController.$commitViewValue (angular.js:24787)
at angular.js:24920
at Scope.$get.Scope.$eval (angular.js:15719)
at Scope.$get.Scope.$apply (angular.js:15818)

您没有注入 $q 服务。

webAppValidation.directive('checkUsername', ['$q','services', ...

我会这样写

webAppServices.factory('usersService', ['$q','$http',

  var endPoint = 'http://localhost:8080/api/user';

  function ($q, $http){
    var _getUsers = function(){
       var deffered = $q.defer();

       $http.get(endpoint)
            .then(
              function(data){ deffered.resolve(data);}),
              function(data){ deffered.reject(data);})
            ).catch(function(error){  $q.reject(error);});

       deffered.promise;

 }
 //...
 //the other methods
 //...
    return{
       getUsers: _getUsers
       //...
    }
;}]);

虽然 $http return 是一个承诺,但最好 return 使用 $q 一个可遵循承诺规范的对象,这样您的服务的用户就不会看到 then ... undefined

感到困惑

您的 webservice 应该公开那些函数,它应该 return $resource 将 return 承诺的对象。对于重新承诺,您需要使用 $resource.$promise 以便承诺链继续。

服务

webAppServices.factory('services', ['$resource',
    function($resource) {
        return {
            users: function() {
                return $resource('http://localhost:8080/api/users', {}, {
                    get: {
                        method: 'GET',
                        isArray: true
                    },
                    add: {
                        method: 'POST',
                        isArray: false
                    },
                    update: {
                        method: 'POST',
                        isArray: false
                    }
                }).$promise; //returning promise
            },

            userName: function() {
                return $resource('http://localhost:8080/api/users/check/:username', {}, {
                    check: {
                        method: 'GET',
                        isArray: false
                    }
                }).$promise; //returning promise
            }
        };
    }
]);

然后在您的服务中注入缺失的 $q

webAppValidation.directive('checkUsername', ['$q', 'services',
function ($q, services) {

感谢您的帮助,现在可以使用了, 我必须注入 '$q' 并在我的验证指令中添加 $promise

webAppValidation.directive('checkUsername', ['$q','services',
function ($q, services) {
    return {
        require: "ngModel",
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$asyncValidators.checkUsername = function(modelValue, viewValue){
               //check username
                return ctrl.$isEmpty(modelValue) || services.userName.check({username:modelValue}).
                        $promise.then(function resolved(){
                            //username exists, this means validation fails
                            return $q.reject('exists');
                        }, function rejected(){
                            //username does not exists, therefore this validation passes
                            return true;
                        });
            };
        }
    };
}]);