stop angular-ui-router navigation until promise is resolved

前端 未结 10 1952
情歌与酒
情歌与酒 2020-12-01 02:44

I want to prevent some flickering that happens when rails devise timeout occurs, but angular doesn\'t know until the next authorization error from a resource.

What h

10条回答
  •  旧时难觅i
    2020-12-01 03:25

    I believe you are looking for event.preventDefault()

    Note: Use event.preventDefault() to prevent the transition from happening.

    $scope.$on('$stateChangeStart', 
    function(event, toState, toParams, fromState, fromParams){ 
            event.preventDefault(); 
            // transitionTo() promise will be rejected with 
            // a 'transition prevented' error
    })
    

    Although I would probably use resolve in state config as @charlietfl suggested

    EDIT:

    so I had a chance to use preventDefault() in state change event, and here is what I did:

    .run(function($rootScope,$state,$timeout) {
    
    $rootScope.$on('$stateChangeStart',
        function(event, toState, toParams, fromState, fromParams){
    
            // check if user is set
            if(!$rootScope.u_id && toState.name !== 'signin'){  
                event.preventDefault();
    
                // if not delayed you will get race conditions as $apply is in progress
                $timeout(function(){
                    event.currentScope.$apply(function() {
                        $state.go("signin")
                    });
                },300)
            } else {
                // do smth else
            }
        }
    )
    
    }
    

    EDIT

    Newer documentation includes an example of how one should user sync() to continue after preventDefault was invoked, but exaple provided there uses $locationChangeSuccess event which for me and commenters does not work, instead use $stateChangeStart as in the example below, taken from docs with an updated event:

    angular.module('app', ['ui.router'])
        .run(function($rootScope, $urlRouter) {
            $rootScope.$on('$stateChangeStart', function(evt) {
                // Halt state change from even starting
                evt.preventDefault();
                // Perform custom logic
                var meetsRequirement = ...
                // Continue with the update and state transition if logic allows
                if (meetsRequirement) $urlRouter.sync();
            });
        });
    

提交回复
热议问题