Search code examples
angularjsangularjs-service

Sharing data between AngularJS services


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.


Solution

  • 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