2

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.

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

Comments

11

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.