为什么我的 $state.go 仅在设置超时内工作

Why my $state.go only working when inside a setTimeout?

本文关键字:设置 超时 工作 我的 state go 为什么      更新时间:2023-09-26

当用户键入/general时,我需要重定向用户/boards。我正在使用$state.go('boards')来实现这一点,但即使没有延迟,它也只有在将其包装在setTimeout函数中时才有效。为什么会有这种行为?

App.randomModule = angular.module('App.randomModule', ['ngRoute', 'ui.router'])
  .config(function ($stateProvider){
    $stateProvider
    .state('general', {
      url: '/general', 
      resolve: {
        redirect: function ($state){
          // Working
          window.setTimeout(function(){
           $state.go('boards');
          }, 0); // Note there's no delay
          // Not working
          $state.go('boards');
        }
      }
    })
  });
setTimeout(function(){}, 0)

下一个即时报价中执行该函数。您的决心:在您执行其他操作之前不会调用重定向。

因此,当您处于当前循环中时,您告诉ui-router:$go('/general') - 所以现在它需要转到常规。但它不会立即这样做,因为它有resolve()!首先,它尝试解析redirect对象,然后执行其$go('/general');

因此,您为摘要周期堆叠了一些更改:- 创建 resolve 对象(也许你在那里返回一个承诺,也许是一个值,也许未定义,没关系)- $state.go('/board')- $state.go('/general')

而且(这里的假设),angular 会看到它在挖掘循环中发生变化,并且会看到即使您调用解析,它也不是最后一个要放置的 URL,它会被覆盖。

但是,当您将setTimeout()放入游戏时,您的go('board')会在摘要循环之后被调用,因此它将执行。

附带说明一下,您可能最好使用 $timeout 而不是 setTimeout。

你为什么要为此使用resolve?只需注入$urlRouterProvider并设置重定向规则:

$urlRouterProvider.when('/general', '/boards');

最好使用 ui 路由器事件。有$stateChangeStart可以帮助您。

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ 
    // your logic
    if (...) {
        event.preventDefault(); 
    }
})

链接: https://github.com/angular-ui/ui-router/wiki#state-change-events