我有一个更改标题和描述的$rootScope.$on("$stateChangeStart")
事件。
而且我必须在我的event
中使用$http
请求后创建的$rootScope
对象。问题是当$stateChangeStart
事件运行时,我的object
是未定义的。
我试图在我的ui-router
州使用resolve
。但它仅适用于控制器,不适用于event
.
您能否帮助我想出一个解决方案,该解决方案将在路由开始(并且$stateChangeStart
事件运行)之前运行我的服务(带有$http
请求),并且在状态更改后它不会再次运行此服务。
我决定尝试用promise
解决这个问题:
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
if ($rootScope.myObj) { // if my "object" was already created
eventLogic();
} else {
getMyObj.init().then(function(res){ //call service that retuns a promise
eventLogic();
});
}
function eventLogic() {
...
}
}
这个解决方案完全解决了我的问题。它等待创建$rootScope.myObj
,并且仅运行此服务一次。