简体   繁体   English

在角配置中使用带有$ http和$ q的服务/提供程序

[英]Using service/provider with $http and $q in angular config

I want to load some configuration to each controller in app.config section. 我想在app.config部分为每个控制器加载一些配置。 Each controller needs a different, but non-mutually-exclusive set of data to be loaded. 每个控制器都需要加载不同但非互斥的数据集。 I can't figure out how to achieve this. 我无法弄清楚如何实现这一目标。

.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'},
    })
}])

However, I don't want to write seperate factories for someConfigA and someConfigD , since they share code. 但是,我不想为someConfigAsomeConfigD编写单独的工厂,因为它们共享代码。 I want something like, 我想要的东西,

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
    };
})

How can I do this? 我怎样才能做到这一点?

It sounds like what you are looking for is $q.all , which you can read about here . 听起来你正在寻找的是$q.all ,你可以在这里阅读。

I also made a fiddle that uses your factory, although I do it in the run method of the module since I didn't want to deal with creating the factory. 我也做了一个使用你的工厂的小提琴 ,虽然我在模块的run方法中这样做,因为我不想处理创建工厂。 It looks something like this: 它看起来像这样:

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

the function in the then is only called when both promises have been resolved (which happen at different times, simulated with $timeout 只有在两个promise都已解决时才会调用then中的函数(在不同的时间发生,使用$timeout模拟)

Now the get functions can be reused, Hope this helped! 现在get函数可以重用了,希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM