在执行配置之前等待运行时的异步调用(Angular JS)

时间:2015-10-22 17:09:57

标签: javascript html angularjs angular-ui-router

我需要在加载任何状态之前解析http调用

angular.module('myModule', [])
    .run(function($http, MyFactory) {
        $http.get('/api..')
           .success(function(data){
                MyFactory.setData(data);
                //Store data in a service
            });
    })
    .config(function($stateProvider) {
        $stateProvider
        .state('main', {...})
        .state('main.app'{
            url: '/app'
            resolve: {
               data: function(MyFactory) {
                  MyFactory.getData();
                // This block needs to be run after my $http call in 'run' has been resolved.
                return ..
               } 
            }
         }
     });
.factory('MyFactory', function () {
     var data = '';
     return {
        setData: function(_data) {
           data = _data
        },
        getData: function() {
           return data;
        }
     } 
};

我尝试将$http作为解决方案放在我的第一个州.main中,但是如果您直接转到.main.app,则第一个解析将在第二个解析后执行。

1 个答案:

答案 0 :(得分:1)

我相信您可以使用以下模式制定依赖性承诺解决方案,其中setData链将在.main中完成,并且当我们在getData中解析.main.app时会满意。无需在.run()中执行此操作,相反,以下是对我认为您要完成的内容的简单解释......

.factory('MyFactory', function($http, $q) {

    function setData() {

        var deferred = $q.defer();

        $http.get('/endpoint').success(function(response) {

            // do something with data - we just want to resolve the response so this block is executed

            deferred.resolve(response)
        });

        return deferred.promise;
    }

    function getData() {
        return $http.get('/endpoint');
    }

    return {
        getData: 'getData',
        storeData: 'storeData'
    }
});
.state('main', {
    resolve : {
        set: ['MyFactory', function(MyFactory) {
            return MyFactory.setData();
        }]
    }
})
.state('main.app', {
    resolve: {
        data: ['set', 'MyFactory', function(saved, MyFactory) {
            // -- set must be resolved
            return MyFactory.getData();
        }]
    }
});