Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs $state and $rootScope.$on($stateChangeStart) issue

I've went through multiple questions but haven't find a solution.

I have an issue with states handling.

$urlRouterProvider.otherwise( function($injector, $location) {
    var $state = $injector.get("$state");
    $state.go("cover");
});

$stateProvider
    .state('auth', {
        url: '/auth',
        templateUrl: '../views/authView.html',
        controller: 'AuthController as auth'
    })
    .state('users', {
        url: '/users',
        templateUrl: '../views/userView.html',
        controller: 'UserController as user'
    })
....

this how routing works in my app.

app.run(function($rootScope, $state, $location) {
    $rootScope.$on('$stateChangeStart', function(event, toState, fromState) {

        //ERROR IS IN THIS BLOCK
        if($rootScope.authenticated && $rootScope.onboard == 0) {

            //event.preventDefault();

            $state.transitionTo("onboard", null, {notify:false});
            $state.go('onboard');
        }
...

Everytime I change my route, that block fires hundred times, but I want it simply check whether user is authenticated and completed some forms or no and if no just redirect to the forms itself.

I've tried different ways with preventDefault(); or without, same issue.

like image 730
user3581552 Avatar asked Sep 20 '15 14:09

user3581552


1 Answers

Firstly, we should always try to check, if user is not already going (being redirected previously) to the state 'onboard'. If yes, stop any other handling ( simply return).

$rootScope.$on('$stateChangeStart', function(event, toState, fromState) {

    // in case, that TO state is the one we want to redirect
    // get out of here   
    if(toState.name === "onboard"){
       return;
    }

    if($rootScope.authenticated && $rootScope.onboard == 0) {

        // this should not be commented
        //event.preventDefault();
        // because here we must stop current flow.. .
        event.preventDefault();

        $state.transitionTo("onboard", null, {notify:false});
        $state.go('onboard');
    }
 ...

Check the angularjs ui-router generates infinite loop

like image 56
Radim Köhler Avatar answered Sep 30 '22 13:09

Radim Köhler