Angular ui路由器(extras)$ stateChangeStart事件触发两次

问题描述 投票:0回答:1

[有人可以向我解释为什么Angular UI Router Extras加法如果我有一些异步ajax检查和$stateChangeStart调用,则触发两次(在init!上)e.preventDefault()事件?

短事件代码示例:

 $rootScope.$on("$stateChangeStart", function (e, toState, toParams, fromState, fromParams, error) {
       console.log("$stateChangeStart");//fired twice
       if(!User.data) {
             e.preventDefault();
             $http.get("https://randomuser.me/api/")
             .success(function(data, status, headers, config) {
                  console.log(data);
                  User.data = data; 
                  $state.go(toState, toParams);
              });
       }              
 });

Full FIDDLE Example

没有额外的功能,一切都按预期工作。

Tnx

javascript angularjs ajax angular-ui-router angular-ui-router-extras
1个回答
0
投票

Angularjs在其摘要周期中进行了多次检查,以检查更改前后,这可能是该周期的一部分。

您可以在$ watch期间看到此行为。

$scope.$watch('myVariable', function( change ){
  if( !change ){ return; }
  // do important things here.
});

在摘要的第一轮change参数将以undefined的形式出现,直到在其他位置设置了[[myVariable。一旦将[[myVariable设置为else-wear,$ watch将再次触发并突破if块,以执行一些实际工作。

如果您的函数属于这种情况,也许您可​​以添加一个if块,并在未定义一个或多个参数或不执行某些值的情况下返回。

$rootScope.$on("$stateChangeStart", function (e, toState, toParams, fromState, fromParams, error) { if( !e || !toStateForExample || anotherParameter ){ return; } console.log("$stateChangeStart");//fired twice if(!User.data) { e.preventDefault(); $http.get("https://randomuser.me/api/") .success(function(data, status, headers, config) { console.log(data); User.data = data; $state.go(toState, toParams); }); } });

© www.soinside.com 2019 - 2024. All rights reserved.