我試圖構建的是一個登錄服務。 我寫了一個工廠,我需要由每個控制器使用。它用於檢查用戶是否已登錄。但我得到這個錯誤:
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);
})
}
});
})();
任何人都可以指出我犯的錯?提前致謝。
缺少工廠返回語句: – Sajal