加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:51:14 所属栏目:安全 来源:网络整理
导读:考虑一下代码: var myApp = angular.module('myApp',[]); 路线: myApp.config(['$routeProvider',function($routeProvider) { $routeProvider.when('/',{ templateUrl: 'app.html',controller:myAppController,resolve:{ resolveData:function(Resolver){
考虑一下代码:
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个调用依赖于第一个调用.

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

您应该使用链接承诺和$q服务来解决您的问题.使用下面的示例代码它应该工作
myApp.factory('Resolver','$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;

              }
          }]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读