返回相互依赖的异步承诺在$ routeProvider决心 [英] Return interdependent async promises in $routeProvider resolve
本文介绍了返回相互依赖的异步承诺在$ routeProvider决心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑code:
var myApp = angular.module('myApp', []);
该路线:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'app.html',
controller:myAppController,
resolve:{
resolveData:function(Resolver){
return Resolver();
}
}
});
});
解析:
myApp.factory('Resolver', ['$http', function($http){
return function(){
return $http({url: '/someurl',method: "GET"}).then(function(data) {
// dependent call 1
$http({url: '/someotherurl',method: "GET" }).then(function(data) {
});
// dependent call 2
$http({url: '/someanotherurl',method: "GET" }).then(function(data) {
});
});
}
}]);
上面我已经嵌套在2个呼叫,因为它们依赖于父调用返回的数据。
Above I have nested 2 calls inside one as they are dependent on the data returned by the parent call.
我想要做什么:返回解析器的时候他们都已经完成了,不只是父母通话
What I want to do: return the Resolver when all of them have completed and not just the parent call.
我不能用$ q.all(),因为通话的2取决于第一次呼叫。
I cannot use $q.all() because 2 of the calls are dependent of the first call.
总之,myAppController必须只有在所有3调用完成后加载。
In short, myAppController must be loaded only after all the 3 calls have completed.
推荐答案
您应该使用链接的承诺,$ Q的服务为您解决问题。只是使用下面的示例code它应该工作
You should be using chaining promise and $q service to solve your problem .Just use the below sample code it should work
myApp.factory('Resolver', ['$http','$q', function ($http,$q) {
return function () {
var deferred = $q.defer();
$http({ url: '/someurl', method: "GET" }).then(function (data) {
return $http({ url: '/someurl', method: "GET" })
}).then(function (data) {
return $http({ url: '/someanotherurl', method: "GET" })
}).then(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
}]);
这篇关于返回相互依赖的异步承诺在$ routeProvider决心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文