【发布时间】:2016-11-02 21:19:46
【问题描述】:
我有一个角度服务:
presence.service('AuthService', function($http, PresenceURLService){
var apiURL = PresenceURLService.apiURL;
this.isLogged = false,
this.access_token = "",
this.login = function(credentials, callback){
var configura = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};
$http({
method:'POST',
url: apiURL+'login',
data: credentials,
config: configura
}).then(function(response){
//success
this.isLogged = response.data.response;
this.access_token = response.data.access_token;
callback(response.data);
}, function(response){
//error
callback(response.data);
});
}
});
每当用户尝试登录时,API 都会返回 tru 或 false,并将其存储在 this.isLogged 中。工作正常。
我为该应用运行了这段代码,以便在用户未登录时停止状态加载:
presence.run(function($rootScope, $location, $state, AuthService) {
$rootScope.$on( '$stateChangeStart', function(e, toState , toParams, fromState, fromParams) {
var isLogin = toState.name === "login";
if(isLogin){
return; // no need to redirect
}
console.log("State we are going to: "+toState.name);
// now, redirect only not authenticated
var logged = AuthService.isLogged;
console.log("Before load must check the AuthService isLogged var: "+logged);
if(logged === false) {
e.preventDefault(); // stop current execution
$state.go('login'); // go to login
}
});
});
在此代码中记录的始终是错误的。但是,以前,当我调用 login() 函数时,它存储为 true。
为什么会丢失数据以及如何获得这种行为?
【问题讨论】:
标签: angularjs angular-services