为什么$ state.go在目标状态或其父级以承诺解析时不起作用

时间:2014-02-26 18:36:29

标签: javascript angularjs angular-ui-router

我尝试使用resolve加载父状态的一些数据,并在应用程序运行时将用户重定向到默认状态:

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

  $stateProvider.state('home', {
    url: '/',
    template: '<div><a ui-sref="home">Start App</a> <a ui-sref="home.main">Home</a> <a ui-sref="home.other">Other state</a><div ui-view>Loading...</div></div>',
    resolve: {
      user: ['$timeout', '$q', 
        function($timeout, $q) {
          var deferred = $q.defer();
          var promise = deferred.promise;
          var resolvedVal = promise.then(function() {
            console.log('$timeout executed');
            return {Id: 12, email: 'some@email.com', name: 'some name'};
          }, function() {
            console.log('Error happend');
          });
          $timeout(function() {
            deferred.resolve();
          }, 2000);
          return resolvedVal;
        }]
      //user: function() {return {id: 222, name: 'testname', email: 'test@em.ail'}; }
    },
    controller: ['$scope', 'user', function($scope, user) {
      $scope.user = user;
    }]
  });

  $stateProvider.state('home.other', {
    url: 'other',
    template: '<div>Your name is {{user.name}}, and email is {{user.email}}</div><div>This is other state of application, I try to make it open as default when application starts, by calling to $state.transitionTo() function in app.run() method</div>',
    resolve: {
      someObj: function() {
        console.log('hello');
        return {someProp: 'someValue'};
      }  
    },
    controller: ['$scope', 'user', function($scope, user) {
      $scope.user = user;
    }]    
  });

}]);  

app.run(['$state', '$rootScope', function ($state, $rootScope) {
  $state.go('home.other');   
}]);

这不会改变地址栏中的url并且不会显示home.other状态的模板(虽然home.state的解析功能已执行且控制台中有'hello')。 但是当我在解析中评论promise函数时,而是将简单的函数返回给对象应用程序重定向,如预期的那样。

此外,而不是$ timeout试图做$ http请求实际上会在那里,但也没有运气。

2 个答案:

答案 0 :(得分:10)

并回答我自己的问题 - 因为在调用$ state.go('home.other')之后,摘要周期开始处理请求的url并且解析函数创建了deffered对象,因此不需要的行为发生了,尽管此对象已解决,状态引擎已经传递到请求的url状态。所以为了防止这种情况,我使用了下面解释的技术:

如果您需要在应用程序启动时放弃在某些情况下执行请求的URL状态解析,您可以使用$ stateChangeStart事件,如下所示:

app.run(['$state', '$rootScope', '$timeout', function ($state, $rootScope, $timeout) {
  var appStarted = 0; // flag to redirect only once when app is started
  $rootScope.$on('$stateChangeStart', 
  function(event, toState, toParams, fromState, fromParams) { 
    if(appStarted) return;
    appStarted = 1;   
    event.preventDefault(); //prevents from resolving requested url
    $state.go('home.other'); //redirects to 'home.other' state url
  });  
}]);

答案 1 :(得分:5)

还有same link provided by user3357257的替代解决方案,我觉得它有点清洁。

app.run(['$state', '$rootScope', '$timeout', function ($state, $rootScope, $timeout) {
  $timeout(function() { $state.go('home.other'); });   
}]);

诀窍是将$state.go()包裹到$timeout()中,以免被覆盖。