在$ routeProvider解析中返回相互依赖的异步promise

Alw*_*ner 8 promise angularjs angularjs-routing

考虑一下代码:

var myApp = angular.module('myApp', []);
Run Code Online (Sandbox Code Playgroud)

路线:

myApp.config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: 'app.html', 
            controller:myAppController, 
            resolve:{
                resolveData:function(Resolver){
                    return Resolver();
                }
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)

解决:

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) {

            });
        });
    }
}]);
Run Code Online (Sandbox Code Playgroud)

上面我在一个内嵌了2个调用,因为它们依赖于父调用返回的数据.

我想做什么:当所有这些都完成后返回解析器,而不仅仅是父调用.

我不能使用$ q.all(),因为其中2个调用依赖于第一个调用.

简而言之,只有在所有3个调用完成后才能加载myAppController.

Aja*_*wal 9

您应该使用链接承诺和$ 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;

              }
          }]);
Run Code Online (Sandbox Code Playgroud)