AngularJS错误:提供程序必须从$get工厂方法返回值

AngularJS error: Provider must return value from $get factory method

本文关键字:get 工厂 返回值 方法 错误 程序 AngularJS      更新时间:2023-09-26

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

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);
                    })
                }
        });
})();

有人能指出我犯的错误吗?提前谢谢。

 .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工厂应该返回一个要由控制器消耗的对象。

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

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

你可以按照John Papa风格指南,更喜欢使用工厂而不是服务。

(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;
}]);
})();

或以下是创建工厂的更好方法:

(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;
}]);
})();