考虑代码:
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 个调用,因为它们依赖于父调用返回的数据。
我想要做的:当所有解析器完成而不仅仅是父调用时返回解析器。
我无法使用 $q.all(),因为其中 2 个调用依赖于第一个调用。
简而言之,myAppController 必须在 3 个调用全部完成后才加载。
最佳答案
您应该使用链接 promise 和 $q 服务来解决您的问题。只需使用下面的示例代码就可以了
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;
}
}]);
关于angularjs - 在 $routeProvider 解析中返回相互依赖的异步 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18010796/