AngularJS错误:提供者必须从$ get factory方法返回值

时间:2016-05-17 10:56:25

标签: javascript angularjs authentication

我尝试构建的是登录服务。 我写了一个工厂,我需要每个控制器使用它。它用于检查用户是否已登录。但是我收到了这个错误:

Provider must return value from $get factory method

我对Angular非常陌生。这是我的索引页面:

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Index Page</title>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
        <script src="assets/lib/angular.js"></script>
        <script src="assets/lib/angular-route.js"></script>

        <script src="app/app.js"></script>
        <script src="app/AuthenticationService.js"></script>
    </head>
    <body>
        <div ng-view></div>
    </body>
</html>

app.js文件:

( function () {

    angular.module('myApp', [
        'ngRoute',
        'ngAnimate',
        'myApp.login',
        'myApp.home',
        'myApp.AuthenticationService'
    ])  
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider
        .when('/login', {
            controller: 'LoginController',
            templateUrl: 'loginView.html',
            controllerAs: 'vm'
        })
        .when('/home', {
            controller: 'HomeController',
            templateUrl: 'HomeView.html',
            controllerAs: 'vm'
        })
        .otherwise({
            redirectTo: '/login'
        });
    }]);    
})();

这是我设立的工厂:

    (function() {

    angular
    .module('myApp.AuthenticationService', [])

    .factory('AuthService', ["$http", "$location", function($http, $location){
        var vm = this;
        vm.checkToken = function(token){
            var data = {token: token};
            $http.post("endpoints/checkToken.php", data).success(function(response){
                if (response === "unauthorized"){
                    console.log("Logged out");
                    $location.path('/login');
                } else {
                    console.log("Logged In");
                    return response;
                }
            }).error(function(error){
                $location.path('/login');
            })

        }

    }]);

    })();

And this is how I inject it in a controller:

(function() {

    angular
        .module('myApp.home', [])

        .controller('HomeController', function($routeParams,AuthService) {
                var vm = this;      

                //If user is not logged in
                var token;
                if (localStorage['token']){
                token = JSON.parse(localStorage['token']);
                } else {
                token = "something stupid";
                }
                AuthService.checkToken(token);

                $scope.logout = function(){
                    var data = {
                        token: token
                    }

                    $http.post('endpoints/logout.php', data).success(function(response){
                        console.log(response)
                        localStorage.clear();
                        $state.go("login");
                    }).error(function(error){
                        console.error(error);
                    })
                }

        });

})();

有谁可以指出我犯的错误?提前谢谢。

3 个答案:

答案 0 :(得分:4)

 .factory('AuthService', ["$http", "$location", function($http, $location){
        var vm = this;
        vm.checkToken = function(token){
            var data = {token: token};
            $http.post("endpoints/checkToken.php", data).success(function(response){
                if (response === "unauthorized"){
                    console.log("Logged out");
                    $location.path('/login');
                } else {
                    console.log("Logged In");
                    return response;
                }
            }).error(function(error){
                $location.path('/login');
            })

        }
       return vm;
    }]);

Angular factory should return an object to be consumed by the controller.

答案 1 :(得分:0)

(function() {

angular
.module('myApp.AuthenticationService', [])

.factory('AuthService', ["$http", "$location", function($http, $location){
    var vm = {};
    vm.checkToken = function(token){
        var data = {token: token};
        $http.post("endpoints/checkToken.php", data).success(function(response){
            if (response === "unauthorized"){
                console.log("Logged out");
                $location.path('/login');
            } else {
                console.log("Logged In");
                return response;
            }
        }).error(function(error){
            $location.path('/login');
        })

    }

    return vm;
}]);

})();

or below is the better way to create factory:

(function() {

angular
.module('myApp.AuthenticationService', [])

.factory('AuthService', ["$http", "$location", function($http, $location){

    var vm = {
        checkToken: checkToken
    };

    function checkToken(token){
        var data = {token: token};
        $http.post("endpoints/checkToken.php", data).success(function(response){
            if (response === "unauthorized"){
                console.log("Logged out");
                $location.path('/login');
            } else {
                console.log("Logged In");
                return response;
            }
        }).error(function(error){
            $location.path('/login');
        })

    }

    return vm;
}]);

})();

答案 2 :(得分:0)

这里的问题是因为您没有在工厂函数中返回对象。在您的情况下,您需要使用.factory()而不是.service()。这是因为您正在使用构造函数(在函数内使用this)。如果您想使用工厂,可以按照以下步骤操作:

.factory('AuthService', ["$http", "$location", function($http, $location){
    var service = {
       checkToken: function() {...}
    };

    return service;
}])

您可以关注John Papa Style Guide,而更喜欢使用工厂代替服务。