Tream
Tream

Reputation: 1054

AngularJS: Connect two services with each other

I have following to services:

dataService (should get data from the apiService, and then sort/group/filter the data). apiService (should get the data from server. Also, when updated data comes in (websockets), the data should be pushed to dataService).

Now, it looks like, two services cant be connected to each other. How can my dataService now get updates? I had following idea, but im not sure, if this is best practice:

What do you think? Is there some better way to do that? Thank you very much!

Edit:

This wont work:

var apiService = angular.module('apiService', []);

apiService.service('apiService', ['$http', 'dataService', function($http, dataService) {
    return {
        foo: "foo"
    };
}]);


var dataService = angular.module('dataService', []);

dataService.service('dataService', ['$http', 'apiService', function($http, apiService) {
    return {
        foo: "foo"
    };
}]);

Edit 2:

Will show me in Firebug:

Error: [$injector:cdep] http://errors.angularjs.org/1.2.26/$injector/cdep[...]

Upvotes: 0

Views: 838

Answers (1)

robinmitra
robinmitra

Reputation: 614

Your services don't work due to cyclic dependency between them.

Your proposed solution should work fine, but can be improved further by using promises, like the pseudo code below:

var apiService = angular.module('apiService', []);

// Note that 'apiService' no longer has 'dataService' as a dependency
apiService.factory('apiService', ['$http',
  function($http) {
    return {
      get: function() {
        // Return $http promise
        return $http.get(...);
      }
    };
  }
]);


var dataService = angular.module('dataService', []);

// Now, only 'dataService' depends on 'apiService'
dataService.factory('dataService', ['$http', 'apiService',
  function($http, apiService) {
    return {
      // This can further return a promise like below
      get: function() {
        return apiService.get()
          // Execute 'then' once the promise returned by the apiService.get() is resolved (i.e. date received)
          .then(function(response) {
            console.log(response);
          })
      }
    };
  }
]);

Upvotes: 1

Related Questions