gpt4 book ai didi

javascript - 注入(inject) Controller 时服务未定义

转载 作者:行者123 更新时间:2023-11-30 15:49:57 26 4
gpt4 key购买 nike

我有一个 Controller ,我已经将一个工厂注入(inject)其中,但是当我对该工厂调用一个方法时,它返回为未定义。不确定我在这里做错了什么。任何帮助将不胜感激。

工厂:

(function(){
'use strict';

// Declare factory and add it 'HomeAutomation' namespace.
angular.module('HomeAutomation').factory('AuthenticationService', ['$http','$localStorage', '$window', function($http, $localStorage, $window){
var service = {};


service.login = Login;
service.logout = Logout;
service.parseJWT = parseJWT;
service.loginStatus = loginStatus;

return service;


function Login(email, password, callback){
$http.post('api/user/login', {email: email, password: password})
.success(function(res){
// Login successful if there is a token in the response.
if(res.token){
// store username and token in local storage to keep user logged in between page refreshes
$localStorage.currentUser = { email: email, token: res.token };

// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = 'Bearer ' + res.token;

callback(true);
}else{
callback(res);
}
}).error(function(err){
console.log(err);
});
}

function Logout(){
$localStorage.currrntUser
}

function parseJWT(token){
var base64URL, base64;

base64URL = token.split('.')[1];
base64 = base64URL.replace('-', '+').replace('_', '/');

console.log(JSON.parse($window.atob(base64)));
}

function loginStatus(){
if($localStorage.currentUser){
return true;
}else{
return false;
}
}
}]);}());

Controller :

(function(){
angular.module('HomeAutomation')
.controller('loginController', ['$scope', '$location', 'AuthenticationService', function($scope, $location, $localStorage, AuthenticationService){
$scope.isLoggedIn = AuthenticationService.logout();

$scope.logUserIn = function(){
AuthenticationService.login($scope.login.email, $scope.login.password, function(result){
if(result === true){
$location.path('/');
}else{
console.log(result);
}
});
};

$scope.logUserOut = function(){
AuthenticationService.logOut();
}
}]);}());

这是导致错误的行:

$scope.isLoggedIn = AuthenticationService.logout();

显然“AuthenticationService”未定义。不知道为什么。

提前致谢。

最佳答案

你弄乱了依赖序列,你需要从 Controller 工厂函数中删除 $localStorage 因为 $localStorage 没有在 Controller 中的任何地方使用并且没有注入(inject)DI 阵列。

.controller('loginController', ['$scope', '$location', 'AuthenticationService', 
function($scope, $location, AuthenticationService){
//^^^^^^^^^^removed $localStorage dependency from here

NOTE: Always make sure when you inject any dependency in DI array, they should used in same sequence in controller function

关于javascript - 注入(inject) Controller 时服务未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com