简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM