Sharing data between AngularJS services

橙三吉。 提交于 2020-01-10 11:48:10

问题


Is there a way to share data between services in AngularJS?

Use case: data aggregation from different services
For example I want a service1 that loads some data from a REST Service. Then another service2 adds additional data to the service1 data from another REST API to create a data aggregation service.

I basically want to separate the services based on the APIs that they use, but still have a service that holds all the data in the end.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/15313205/sharing-data-between-angularjs-services

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