Angular应用程序中的服务未定义

时间:2016-09-13 22:21:27

标签: javascript angularjs

我知道这个问题之前已经得到了回答,但说​​实话,我无法在我的程序环境中做出任何答案的正面或反面。我的服务如下:

(function() {
angular
    .module('datingApp')
    .service('authentication', authentication);

authentication.$inject = ['$window'];
authentication.$inject = ['$http'];

function authentication($window, $http) {

    var saveToken = function(token) {
        $window.localStorage['token'] = token;
    };

    var getToken = function() {
        return $window.localStorage['token'];
    };

    var register = function($http, user) {
        return $http({
            method: 'post',
            url: '/users/register',
            data: user
        })
    };

    ...

    return {
        saveToken: saveToken,
        getToken: getToken,
        register: register
    }

}

一切都很好,除非我尝试在我的控制器中使用寄存器功能"无法读取属性'注册'未定义"弹出。这些函数都不起作用,甚至是我写的虚函数。

我的控制器看起来像这样:

angular.module('datingApp').component('signupForm', {
    templateUrl: '/public/templates/signup.html',
    controller: function signupCtrl($scope, authentication) {
    //using an immediate function to generate ages 18-99

    $scope.saveData = function(authentication) {
    ...

    authentication.register(x).then(function() { console.log("user saved") }, function() { console.log("failure") });
};

错误堆栈是这样的:

ypeError: Cannot read property 'register' of undefined
at m.$scope.saveData (signup.form.component.js:72)
at fn (eval at compile (angular.min.js:1), <anonymous>:4:215)
at b (angular.js:15694)
at e (angular.js:25622)
at m.$eval (angular.js:17444)
at m.$apply (angular.js:17544)
at HTMLButtonElement.<anonymous> (angular.js:25627)
at HTMLButtonElement.dispatch (jquery.min.js:3)
at HTMLButtonElement.q.handle (jquery.min.js:3)

我做错了什么?

1 个答案:

答案 0 :(得分:1)

看起来您在saveData()函数中使用同名 authentication 的本地变量覆盖原始注入服务,然后声明但未定义。因此,只需尝试从saveData()函数中删除身份验证变量:

angular.module('datingApp').component('signupForm', {
  templateUrl: '/public/templates/signup.html',
  controller: function signupCtrl($scope, authentication) {
  //using an immediate function to generate ages 18-99

  $scope.saveData = function() {
  ...

  authentication.register(x).then(function() { console.log("user saved") }, function() { console.log("failure") });

};

BTW:你可以将这两行结合起来:

authentication.$inject = ['$window'];
authentication.$inject = ['$http'];

成一个:

authentication.$inject = ['$window', '$http'];