Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

angularjs - Return interdependent async promises in $routeProvider resolve

Consider the code:

var myApp = angular.module('myApp', []);

The routes:

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

Resolve:

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

            });
        });
    }
}]);

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.

I cannot use $q.all() because 2 of the calls are dependent of the first call.

In short, myAppController must be loaded only after all the 3 calls have completed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

              }
          }]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...