angularjs - Angular JS service dependency injection error -
i new angular have been trying asynchronous validation username availability , getting "cannot read property 'username' of undefined" here service code
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} }) };}]);
here directive code passes username validation
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, means validation fails return $q.reject('exists'); }, function rejected(){ //username not exists, therefore validation passes return true; }); }; } }; }]);
and getting in console
typeerror: cannot read property 'username' of undefined @ link.ctrl.$asyncvalidators.checkusername (validations.js:56) @ angular.js:24723 @ foreach (angular.js:350) @ processasyncvalidators (angular.js:24722) @ ngmodelcontroller.$$runvalidators (angular.js:24681) @ ngmodelcontroller.$$parseandvalidate (angular.js:24819) @ ngmodelcontroller.$commitviewvalue (angular.js:24787) @ angular.js:24920 @ scope.$get.scope.$eval (angular.js:15719) @ scope.$get.scope.$apply (angular.js:15818)
you not injecting $q
service.
webappvalidation.directive('checkusername', ['$q','services', ...
i write this
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 //... } ;}]);
although $http
returns promise, better return $q
thenable object follow specifications of promises, users of services didnt confused seeing then ... undefined
Comments
Post a Comment