0

My question is similar so this one:stop angular-ui-router navigation until promise is resolved

Still, none of the answers seem to solve this issue.

My application stores a cookie with a token. When the page is loaded (after a F5 for example), the application checks for the cookie and if found, it uses the token to load the user settings, which are loaded from a web service. These settings are needed to get all other information from the other web services which my controllers will call, so the settings have to be loaded before the page may render.

This is my current code:

    $rootScope.$on( '$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
        e.preventDefault();

        authentication.checkCookie(function() {
            if (toState.name == 'login'){
                if(authentication.getLoginData()) {
                    //e.preventDefault();
                    $state.go('pricelist');
                }
            } else {
                if(!authentication.getLoginData()) {
                    //e.preventDefault();
                    $state.go('login');
                }
            }

            // No redirect is needed - now render the page requested
            $urlRouter.sync();
        });

    });

Unfortunately, this code does not work: it just causes an endless loop.

How can I make sure the rendering only continues as soon as the cookie is checked and the user settings are loaded (this also gets done in checkCookie)?

Community
  • 1
  • 1
Bv202
  • 3,924
  • 13
  • 46
  • 80

1 Answers1

0

I have managed to solve this issue by using another answer in the mentioned link:

    $rootScope.$on( '$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
        if ($rootScope.stateChangeBypass) {
            $rootScope.stateChangeBypass = false;
            return;
        }

        e.preventDefault();

        authentication.checkCookie(function() {
            $rootScope.stateChangeBypass = true;
            if (toState.name == 'login'){
                if(authentication.getLoginData()) {
                    $state.go('pricelist');
                } else {
                    $state.go(toState, toParams);
                }
            } else {
                if(!authentication.getLoginData()) {
                    $state.go('login');
                } else {
                    $state.go(toState, toParams);
                }
            }
        });

    });

It's not really a clean solution, but it works.

Bv202
  • 3,924
  • 13
  • 46
  • 80