2017-10-26 10 views
0

サービスを持っています: service.getMarketedPrograms = function(){ return $ http.get(archApiUrl + "program/marketed-program" )その後。(関数(結果){ return result.data; }); };

私は上記でサービスを追加したい:

service.getEligibility =機能(のparams){ リターン$ http.get(maverickApiUrl + "引用/ getEligibility"、{のparams:のparams})。その後、 (transformEligibility); };私は正しく、あなたが最初に両方の結果を取得し、返すために何を決定する必要があります理解していれば

合併後、私は最終的に1

答えて

0

をフィルタリングします。

あなたは$ qをサービスを注入(約束をangularjs)し、その後、このようなコードを使用する必要があります。

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 
}) 
+0

おかげで、私の場合、私は別の でのサービスの両方を持っている:だから、whenAllDone機能は両方コントローラーが自分のタスク($scope.self = true)を行っているときにのみ呼び出されます2つの異なる.jsファイルのコントローラ –

+0

@DebasmitaSwain、なぜあなたは両方のサービスをコントローラに注入できないのですか?または、このタスクを完了するための別の第3のサービスを作成しますが、正直言って私はすべてがはるかに単純であり、間違った方向に進んでいると思います –

0

あなたがそれらすべてを同期させるために、二つの異なるコントローラと2つのサービスを持っている場合は、あなたがeventsメカニズムを使用する必要があり、すなわち$broadcastおよび$onの方法。あなたの答えのための

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>