我想在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'},
})
}])
但是,我不想为 someConfigA
和 someConfigD
编写单独的工厂,因为它们共享代码。我想要这样的东西,
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
};
})
我该怎么做?
听起来您正在寻找的是 $q.all
,您可以在此处阅读。
我还制作了一个使用您的工厂的小提琴,尽管我在模块的 run 方法中这样做,因为我不想处理创建工厂。它看起来像这样:
f.configA = function(){
var get12 = $q.all([
get1().then(thenFn),
get2().then(thenFn)
]).then(function() {
console.log('both resolved');
});
return get12;
};
then 中的函数仅在两个承诺都已解决时才被调用(这些承诺发生在不同的时间,用 $timeout
模拟
现在get函数可以重用了,希望这有帮助!