将$ http.get()与另一个$ http.get()/ angular合并

时间:2017-10-26 08:10:06

标签: angularjs

我有服务:  service.getMarketedPrograms = function(){             return $ http.get(archApiUrl +" program / marketed-program")。then(function(result){                 return result.data;             });         };

我想用以上内容附加服务:

service.getEligibility = function(params){             返回$ http.get(maverickApiUrl +" quote / getEligibility",{params:params})。then(transformEligibility);         };

合并后我想过滤最后一个

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要首先得到两个结果,然后决定要返回什么。

你需要注入$ q服务(angularjs promises),然后使用这样的代码:

var promises = [getMarketedPrograms(), getEligibility()];
$q.all(promises).then(function(results){ //array of results
     console.log(results[0]); //marketedPrograms result
     console.log(results[1]); //getEligibility result
     return results[0]; //for example, or do whatever you need
})

答案 1 :(得分:0)

如果您有两个不同的控制器和两个服务,要同步它们,您应该使用events机制,即$broadcast$on方法。因此,仅当两个控制器完成其任务(whenAllDone)时才会调用$scope.self = true函数:



function controllerFactory(timeout, name){
  return function($scope, $timeout){
    var self = this; 
    var outerResult;
    $scope.name = name;

    whenAllDone = (data) => {
      console.log(`Sync ${name} - selfResult: ${timeout}, outerResult: ${data}`);
    }

    $scope.$on('done', (x, arg) => {          
      if(arg.ctrl != self){
        $scope.outer = true;  
        outerResult = arg.val;
        if($scope.self)
          whenAllDone(arg.val);
      }
    });
    //mimic for getEligibility and getMarketedPrograms
    $timeout(() => {    
      $scope.self = true;    
      $scope.$parent.$broadcast('done', { ctrl: self, val: timeout });    
      if($scope.outer)
        whenAllDone(outerResult);
    }, timeout);
  }
}

angular.module('app', [])
.controller('ctrl1', controllerFactory(2000, 'ctrl1'))
.controller('ctrl2', controllerFactory(5000, 'ctrl2'))

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app'>
  <script type="text/ng-template" id="myTemplate">       
      <h4>{{name}}:</h4>
      <span ng-style="{'background-color': self ? 'green' : 'white'}">self</span>
      <span ng-style="{'background-color': outer ? 'green' : 'white'}">outer</span>            
  </script>

  <div ng-controller='ctrl1' ng-include="'myTemplate'"></div>
  <div ng-controller='ctrl2' ng-include="'myTemplate'"></div>
</div>
&#13;
&#13;
&#13;