Sharing data between AngularJS services

╄→гoц情女王★ 提交于 2019-11-30 07:44:05

Create a third service that uses the $q deferred library to combine the promises from the 2 API REST calls using $q.all().

Then pass this third service to your controller as a dependency and use $q.then() to combine the results:

var app = angular.module('angularjs-starter');

app.factory('API_1',function($http){    
      return $http.get('dataSource-1.json');   
})

app.factory('API_2',function($http){    
      return $http.get('dataSource-2.json');   
});

app.factory('API_3',function($q,API_1,API_2){ 
 return $q.all([API_1,API_2]);
})
/* add "$q" and "API_3" as dependencies in controller*/
app.controller('MainCtrl', function($scope,$q,API_3) {

  $q.when(API_3).then(function(results) {
    /* combine the 2 API results arrays*/
    $scope.combinedData=[results[0].data,results[1].data];    

  });    


});

DEMO: Plunker Demo

Since a service can depend on another service, this will work:

myApp.factory('myService1', function() {});
myApp.factory('myService2', function(myService1) {});

Note that they can't both depend on each other, or you'll get a Circular dependency error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!