AngularJS:出现“[...] 不是函数”错误

AngularJS: Getting a "[...] is not a function" error

我收到 "Base64.encode is not a function" 错误,但我不知道为什么:

以下控制器 "login-controller" 使用登录服务:

    angular.module('app')
    .controller('login-controller',
     ['$scope', '$location', '$http', 'LoginService',  
     function($scope, $location, $http, LoginService) {
     ...
        if(LoginService.login($scope.user.name, $scope.user.password) == true)
        {
            $location.path('/chooseMandantAsk')
        }
        else
        {
            $scope.wrongCredentials = true;
        }
    ...
    }]);

下面的LoginService使用了Service Base64的函数:

angular.module('app')
       .service('LoginService', ['$location', '$http', 'Base64', function ($http, Base64) {

    ...

this.login = function (name, password){

            user.auth= "Basic " + Base64.encode(name + ":" + password);
            $http.defaults.headers.common.Authorization = user.auth;
            $http.get(url+'/login')
                .success(function(){  
                     return true;
                 })
                .error(function(){
                    user.auth = "";
                    delete $http.defaults.headers.common['Authorization'];
                    return false;
                });
        };

    ...

}]);

Base64 服务有一个名为 encode 的方法:

angular.module('app').factory('Base64', function () {


    var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

        return {
            encode: function (input) {

                ...

                return output;
            },
            decode: function (input) {

                ...

                return output;
            }
        };
 });

找到了 Base64 服务,我之前用另一种方式使用了 Base64.encode 方法并且它有效。

谁能帮我告诉我这个错误是什么意思?

BR

马蒂亚斯

我认为您在注入依赖项时遗漏了 $location -

service('LoginService', ['$location', '$http', 'Base64', function ($location, $http, Base64)

这就是您收到错误的原因。

您的登录服务声明缺少 $location 依赖项,应该是:

angular.module('app')
       .service('LoginService', ['$location', '$http', 'Base64', function ($location, $http, Base64) {