2014-10-30 77 views
0

我是新的Angularjs开发人员。我想用PHP身份验证登录页面,当我提交表单时,它运行$ scope.login代码。Angularjs执行工厂时出错

我有角这样的代码在工厂这个

var module = angular.module('figi-login', ['onsen']); 

      module.controller('AppController', function($scope) { }); 
      module.controller('PageController', 
      ['$scope', '$rootScope', '$location', 'AuthenticationService', 
      function($scope,$http,$location, AuthenticationService) { 
      ons.ready(function() { 
       // AuthenticationService.ClearCredentials(); 
       $scope.formData = {}; 

       $scope.login = function(){ 
        AuthenticationService.Login($scope.formData) 
         .success(function(data){ 
          alert(data); 
         }); 
       }; 
      }); 

      }]).factory('AuthenticationService', 
      ['$http','$rootScope', 
      function($http,$rootScope){ 
       var service = {}; 

       service.Login = function(formData){ 
        return $http({ 
         method : 'POST', 
         url  : 'http://10.0.2.2/demo/api/login.php', 
         data : $.param(formData), 
         headers : {'Content-Type':'application/x-www-form-urlencoded'} 
        }); 

       }; 
      }]); 

执行登录时,应该调用service.Login。我得到这样的错误

TypeError: Cannot read property 'Login' of undefined

我的代码有什么问题?

回答

1

你忘了你的的AuthenticationService工厂返回service

return service; 

见注释行在工厂的末尾:

.factory('AuthenticationService', 
     ['$http','$rootScope', 
     function($http,$rootScope){ 
      var service = {}; 

      service.Login = function(formData){ 
       return $http({ 
        method : 'POST', 
        url  : 'http://10.0.2.2/demo/api/login.php', 
        data : $.param(formData), 
        headers : {'Content-Type':'application/x-www-form-urlencoded'} 
       }); 
      }; 
      return service; //this line is missing 
     }]) 
-1

你需要重新写你的工厂像这样:

.factory('AuthenticationService', 
     ['$http','$rootScope', 
     function($http,$rootScope){ 
      return{ //The return will make your function available in the controller 
       Login: function(formData){ 
        return $http({ 
         method : 'POST', 
         url  : 'http://10.0.2.2/demo/api/login.php', 
         data : $.param(formData), 
         headers : {'Content-Type':'application/x-www-form-urlencoded'} 
        }); 
       }; 
      } 
}]); 

可以这样写:服务风格:

.service('AuthenticationService', 
     ['$http','$rootScope', 
     function($http,$rootScope){ 
      this.Login = function(formData){ 
       return $http({ 
        method : 'POST', 
        url  : 'http://10.0.2.2/demo/api/login.php', 
        data : $.param(formData), 
        headers : {'Content-Type':'application/x-www-form-urlencoded'} 
       }); 
      }; 
}]); 

这两种写法都比较传统。你可以打电话给他们:

AuthenticationService.Login($scope.formData)