0
votes

I'm using UI-Router and check existing token for every state start to change. This error only happen when first load of the page. If I refresh the page it's gone.

Here is my rootscope that i think is the error:

 .run(['$rootScope', '$location', '$state', '$http', '$window', 'APIROOT', function ($rootScope, $location, $state, $http, $window, APIROOT) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        var isLogin = toState.name === "login";
        if (isLogin) {
            return;
        }
        var userInfo = $window.sessionStorage.token;
        if (!userInfo) {
            event.preventDefault();
            $state.go('login');
        } else {
            $http.get(APIROOT + 'check_token').then(function(resp){
                return true;
            }).then(function(err){

            })
        }
    });
}]);

My Controller:

angular.module('app')
.controller('AppCtrl', ['$http', '$scope', '$window', 'APIROOT', AppCtrl]);

function AppCtrl($http, $scope, $window, APIROOT) {
    var date = new Date();
    var year = date.getFullYear();

    $scope.main = {
       name: $window.sessionStorage.getItem('name'),
       brand: 'Brand',
       year: year
    };
}

First solution that i found is change "$stateChangeStart" to "$stateChangeSuccess" but I want it to check before it change successfully.

What should i Fix?

1
i think thats not the issue update your controller code - ngLover
Thanks you make me realize my appctrl call session which is undefined. - ssuhat

1 Answers

0
votes

I realize my AppCtrl call $window.sessionStorage.getItem('name') which is undefined.

So i modify it:

angular.module('app')
.controller('AppCtrl', ['$http', '$scope', '$window', 'APIROOT', AppCtrl]);

function AppCtrl($http, $scope, $window, APIROOT) {
    var date = new Date();
    var year = date.getFullYear();
    if ($window.sessionStorage.getItem('name')) {
    var name = $window.sessionStorage.getItem('name');
     } else {
        var name = "";
     }
    $scope.main = {
       name: name
       brand: 'Brand',
       year: year
    };
}