在Angular配置中使用$http和$q的服务/提供者

3

我想在app.config部分为每个控制器加载一些配置。每个控制器需要加载不同但不互斥的数据集。我无法弄清如何实现这一点。

.config(['$routeProvider', '$locationProvider', 
        function($routeProvider, $locationProvider){


    $routeProvider
    .when('/', {
        templateUrl: "partials/pages/dashboard.html",
        controller: "dashboard_controller",
        resolve: { dash_config: 'SomeConfigD'},
    })
    .when('/a', {
        templateUrl: "partials/pages/a.html",
        controller: "a_controller",
        resolve: { dash_config: 'SomeConfigA'},
    })
}])

然而,我不想为someConfigAsomeConfigD编写单独的工厂,因为它们共享代码。我需要类似于以下内容的东西:

app.factory('configFactory', function(...){
    var factory = ;

    function get1(){
        // some $http calls here and return a promise
    }

    function get2(){
        // some $http calls here and return a promise
    }

    function get3(){
        // some $http calls here and return a promise
    }
    factory.configA = function(){
        // return a promise to resolve both get1 and get2
    };
    factory.configD = function(){
        // return a promise to resolve both get2 and get3
    };
})

我该如何做到这一点?
1个回答

0

听起来你需要的是$q.all,你可以在这里阅读相关内容。

我还制作了一个fiddle,使用了你的工厂,尽管我是在模块的运行方法中完成的,因为我不想处理创建工厂的问题。它看起来像这样:

f.configA = function(){
    var get12 = $q.all([
        get1().then(thenFn),
        get2().then(thenFn)
    ]).then(function() {
        console.log('both resolved');
    });
    return get12;
};

当两个承诺都已解决时(使用$timeout模拟不同时间),才会调用then中的函数。

现在可以重复使用get函数了,希望这有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接