在初始化路由之前发送$http请求

Send $http request before initialize routing?

本文关键字:http 请求 初始化 路由      更新时间:2023-09-26

我有一个更改标题描述$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,并且仅运行此服务一次。