Angular-ui-路由器:跨状态转换进行异步调用
Angular-ui-router: Making asynchronous call across state transition
我正在尝试对新的 .state
进行由 onEnter 触发的异步 API 调用
onEnter: function(StatFactory){
StatFactory.getStats(function(res){
console.log("callback");
});
}
到目前为止我注意到的是它首先调用异步函数,然后为新状态实例化控制器,最后触发回调。
该函数将更新工厂内部的数据,但不会更新 $scope。
我想也许我需要在新的 $scope 上强制 $apply,但我不知道该怎么做。
有什么想法吗? (我是新手)
据我所知,onEnter
没有为您提供 $scope
来绑定结果。
您可以在控制器创建时调用该函数(IE 控制器的定义块)或使用 resolve
状态参数(注意:如果异步函数失败,这将导致状态不被激活)。
这里有一个 resolve
的例子:
$stateProvider.state('home', {
...
//Will wait for the getStats call to end. You can inject the stats to the controller now.
resolve: {
stats: function(StatFactory) { return StatFactory.getStats(); }
},
controller: function($scope, stats){
//Use stats
$scope.stats = stats;
}
});
我正在尝试对新的 .state
进行由 onEnter 触发的异步 API 调用onEnter: function(StatFactory){
StatFactory.getStats(function(res){
console.log("callback");
});
}
到目前为止我注意到的是它首先调用异步函数,然后为新状态实例化控制器,最后触发回调。
该函数将更新工厂内部的数据,但不会更新 $scope。
我想也许我需要在新的 $scope 上强制 $apply,但我不知道该怎么做。
有什么想法吗? (我是新手)
据我所知,onEnter
没有为您提供 $scope
来绑定结果。
您可以在控制器创建时调用该函数(IE 控制器的定义块)或使用 resolve
状态参数(注意:如果异步函数失败,这将导致状态不被激活)。
这里有一个 resolve
的例子:
$stateProvider.state('home', {
...
//Will wait for the getStats call to end. You can inject the stats to the controller now.
resolve: {
stats: function(StatFactory) { return StatFactory.getStats(); }
},
controller: function($scope, stats){
//Use stats
$scope.stats = stats;
}
});