app.run中$ stateChangeStart内的$ state.go无法正常工作

时间:2015-05-14 21:02:03

标签: javascript angularjs angular-ui-router

注意:这是一个示例代码,window.has_redirected只是为了让问题更容易。

此代码不会重定向到dashboard

我已经在线阅读了它之所以无法正常工作的原因是$state还没有准备好......但是我在网上看到的教程正在做一些非常类似的事情。此

我该如何解决?

(function(){
"use strict";

angular.module('app.routes').config( function($stateProvider, $urlRouterProvider ) {

    $urlRouterProvider.otherwise('/');

    $stateProvider
    .state('login',{
        url: '/',
        ...
    })
    .state('dashboard', {
        url: '/dashboard',
        ...
    });


} ).run( function( $rootScope, Users, $state ) {
    $rootScope.$on( "$stateChangeStart", function(event, toState, toParams
                                                     , fromState, fromParams){

        if ( !window.has_redirected ){
            window.has_redirected = true;
            window.console.log('going to dashboard');
            $state.go('dashboard');
        }

    });
} );
})();

1 个答案:

答案 0 :(得分:7)

a working plunker

你几乎就在那里......我们真正需要的是停止执行流程:

event.preventDefault();

将停止当前状态更改,并将重定向$state.go()

$rootScope.$on( "$stateChangeStart", function(event, toState, toParams
                                                 , fromState, fromParams){

  // I would always check if we are not already on the way
  // to the "redirection" target. 
  var isGoingToDashboard = toState.name === "dashboard";
  if(isGoingToDashboard)
  {
    return;
  }

  // this remains
  if ( !window.has_redirected ){
      window.has_redirected = true;
      console.log('going to dashboard');

      // HERE is the essential breaker of the execution
      event.preventDefault();
      $state.go('dashboard');
  }
});

action here

中查看