角度服务属性未定义 - Typescript

时间:2016-08-19 19:34:18

标签: angularjs authentication typescript angular-ui-router angular-services

我试图在我的Angular 1.5x应用程序中保持身份验证状态,该应用程序是用typescript编写的。

我这样做的方式最简单:属性authenticatedtruefalse

登录成功后,我正在从我的登录控制器将我的身份验证服务中的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属性会一直存在。我没有正确使用服务/设置属性吗?

0 个答案:

没有答案
相关问题