服务之间的循环依赖

时间:2014-04-11 16:02:00

标签: angularjs

我有以下情况:

我有以下服务:

angular.module('countries.services', [
  'language.services'
])

.service('CountriesService', ['LanguageService', '$http', function(LanguageService, $http) {

  this.fetchCountries = function() {
    $http.get('myaddress.com/' + LanguageService.currentLanguage).then(function() {
     //do something
    });
  };
}]);

angular.module('language.services', [
  'countries.services'
])

.service('LanguageService', ['CountriesService', function(CountriesService) {
  this.currentLanguage = null;
  this.setLanguage = function(l) {
    currentLanguage  = l;
    CountriesService.fetchCountries();
  };
}]);

这背后的逻辑是,每次选择语言时,我都希望以所选语言获取国家/地区列表。每当我调用CountriesService.fetchCountries()时,我也希望将当前选择的语言用作翻译国家/地区的语言。

对我而言,这是非常正常的情况。有没有办法可以在Angular中解决这个问题?

2 个答案:

答案 0 :(得分:0)

您可以将当前语言作为参数传递给fetchCountries方法。

CountriesService.fetchCountries(this.currentLanguage);

this.fetchCountries = function(language) {
    $http.get('myaddress.com/' + language).then(function() {
     //do something
    });
};

或者,您可以使用$ rootScope存储当前语言。像这样:

angular.module('language.services', [
'countries.services'
])

.service('LanguageService', ['$rootScope', 'CountriesService', function($rootScope, CountriesService) {
  this.currentLanguage = null;
  $rootScope = this.currentLanguage;

  this.setLanguage = function(l) {
    currentLanguage  = l;
    CountriesService.fetchCountries();
    $rootScope = this.currentLanguage;
  };
}]);

angular.module('countries.services', [])

.service('CountryService', ['$rootScope', '$http', function($rootScope, $http) {

  this.fetchCountries = function() {
    $http.get('myaddress.com/' + $rootScope.currentLanguage).then(function() {
     //do something
    });
  };
}]);

答案 1 :(得分:0)

您需要创建一个经销商服务(或接口),其中包含您正在使用它们的服务(或接口)的参考。您应该使用此经销商服务,而不是之前尝试使用它们的每个参考服务。