在 $routeProvider 解析中返回相互依赖的异步承诺 [英] Return interdependent async promises in $routeProvider resolve
问题描述
考虑代码:
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 服务来解决您的问题.只需使用下面的示例代码,它应该可以工作
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屋!