我试图在我的Angular 1.5x应用程序中保持身份验证状态,该应用程序是用typescript编写的。
我这样做的方式最简单:属性authenticated
是true
或false
。
登录成功后,我正在从我的登录控制器将我的身份验证服务中的authenticated
属性设置为true
:
this.loginService.Authenticate(this.username, this.password)
.then(function (response) {
if (response.success) {
self.authenticationService.SetAuthentication(true);
self.state.go('Main.Dashboard');
}
});
身份验证服务:
module app.Services {
export interface IAuthenticationService {
SetAuthentication(authenticated: boolean): ng.IPromise<any>;
GetAuthentication(): ng.IPromise<boolean>;
authenticated: boolean;
}
export class AuthenticationService extends Services.HttpHandlerService {
authenticated: boolean;
SetAuthentication(authenticated: boolean) {
this.authenticated = authenticated;
}
GetAuthentication() {
return this.authenticated;
}
}
angular.module('myApp').service('authenticationService', AuthenticationService);
}
这是按设计工作的。 isAuthenticated
函数中的stateChangeStart
变量(位于我的app.ts
内)设置为true,用户现在可以导航到信息中心:
stateChangeStart
的运行块中的 app.ts
函数:
$rootScope.$on('$stateChangeStart', stateChangeStart);
function stateChangeStart(event: any, toState: angular.ui.IState, toParams: any, from: angular.ui.IState, fromParams: any) {
var isAuthenticated = authenticationService.GetAuthentication();
if ((toState.data.authNeeded) && !isAuthenticated) {
event.preventDefault();
$state.transitionTo('Authentication.Login');
}
$log.debug('$stateChangeStart', toState, toParams, from, fromParams);
}
当用户刷新仪表板时出现问题。这再次触发stateChangeStart
方法,但这次触发.GetAuthentication()
函数时,它返回undefined
。我以为authentication
中的AuthenticationService
属性会一直存在。我没有正确使用服务/设置属性吗?