Why does AngularJS with ui-router keep firing the $stateChangeStart event?

后端 未结 6 1605
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 18:29

I\'m trying to block all ui-router state changes until I\'ve authenticated the user:

$rootScope.$on(\'$stateChangeStart\', function (event, next, toParams) {         


        
6条回答
  •  失恋的感觉
    2020-12-04 18:56

    I also had this issue. Below is the code to workaround, which inspired by angular-permission project.

    The main concept is to add a flag($$finishAuthorize) into state manually, and break the infinite loop by this flag. Another point we need to be aware is the {notify: false} option of $state.go, and broadcast "$stateChangeSuccess" event manually.

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        if (toState.$$finishAuthorize) {
            return;
        }
        if (!authenticated) {
            event.preventDefault();
            toState = angular.extend({'$$finishAuthorize': true}, toState);
    
            // following $timeout is emulating a backend $http.get('/auth/') request
            $timeout(function() {
                authenticated = true;
                $state.go(toState.name, toParams, {notify: false}).then(function() {
                    $rootScope.$broadcast('$stateChangeSuccess', toState, toParams, fromState, fromParams);
                });
            },1000)
        }
    );
    

提交回复
热议问题