[有人可以向我解释为什么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);
});
}
});
没有额外的功能,一切都按预期工作。
Tnx
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);
});
}
});