2016-02-10 22 views
1

在AngularJS我控制器如下:AngularJS - XX不是一个函数

function LoginController($scope, $rootScope, $location, $cookieStore, UserService) { 

    $scope.rememberMe = false; 

    $scope.login = function() { 
     UserService.authenticate($.param({ 
      username: $scope.username, 
      password: $scope.password 
     }), function(authenticationResult) { 
      var authToken = authenticationResult.token; 
      $rootScope.authToken = authToken; 
      if ($scope.rememberMe) { 
       $cookieStore.put('authToken', authToken); 
      } 
      UserService.get(function(user) { 
       $rootScope.user = user; 
       $location.path("/"); 
      }); 
     }); 
    }; 

    $scope.register = function() { 
     UserService.register($.param({ 
      username: $scope.username, 
      password: $scope.password 
     }), function(authenticationResult) { 

     }); 
    }; 
}; 

和服务工厂:

var services = angular.module('exampleApp.services', ['ngResource']); 

services.factory('UserService', function($resource) { 
    return $resource('rest/user/:action', {}, { 
     authenticate: { 
      method: 'POST', 
      params: { 
       'action': 'authenticate' 
      }, 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded' 
      } 
     } 
    }, { 
     register: { 
      method: 'POST', 
      params: { 
       'action': 'register' 
      }, 
      headers: { 
       'Content-Type': 'application/x-www-form-urlencoded' 
      } 
     } 
    }); 
}); 

当我试图达到在注册浏览器功能,我得到 TypeError: UserService.register is not a function我缺少什么?

我读过这篇文章:Angular - TypeError: XX is not a function看起来很相似,但我不明白。

回答

3

您引用的答案(仅限于我的答案),与您期望实现的答案完全不同。

你有错误的$资源对象格式,自定义$资源方法应该在单个对象中,而不是让它们分开。

代码

services.factory('UserService', function($resource) { 
    return $resource('rest/user/:action', {}, { 
    authenticate: { 
     method: 'POST', 
     params: { 
     'action': 'authenticate' 
     }, 
     headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
     } 
    }, 
    register: { 
     method: 'POST', 
     params: { 
     'action': 'register' 
     }, 
     headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
     } 
    } 
    }); 
}); 
+0

这是工作!感谢帮助! – Araneo

+0

@Araneo很高兴知道..谢谢:) –

+0

@Araneo继续前进,并将答案标记为正确..因为它确实帮了你。谢谢:) –

相关问题