angularjs:我可以结合这项服务吗?

时间:2013-08-22 23:06:35

标签: javascript angularjs

我需要加载两个JSON文件。我现在通过单独的服务加载它们,如下所示:

app.factory('AventosService', function($rootScope, $http)
{
  var data = [];
  return {
    promise: null,
    loadAventosJson: function()
    {
      this.promise = $http.get('resources/json/aventos.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('AventosJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getAventosJson: function()
    {
      if (!data.length && !this.promise) this.loadAventosJson();
      return data;
    }
  }
});

app.factory('PartsService', function($rootScope, $http)
{
  var data = [];
  return {
    promise: null,
    loadPartsJson: function()
    {
      this.promise = $http.get('resources/json/part_numbers.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('PartsJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getPartsJson: function()
    {
      if (!data.length && !this.promise) this.loadPartsJson();
      return data;
    }
  }
});

要拨打该服务,我只需执行以下操作:

$scope.aventosJson = AventosService.getAventosJson();

$scope.partsJson = PartsService.getPartsJson();

然后我检查两个事件是否都是火灾。这两项活动均为AventosJsonLoadedPartsJsonLoaded

1 个答案:

答案 0 :(得分:1)

你走了:

app.factory('TheService', function($rootScope, $http)
{
  var data = [];
  return {
    aventosPromise:null,
    loadAventosJson: function()
    {
      this.aventosPromise = $http.get('resources/json/aventos.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('AventosJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getAventosJson: function()
    {
      if (!data.length && !this.aventosPromise) this.loadAventosJson();
      return data;
    },
    partsPromise: null,
    loadPartsJson: function()
    {
      this.partsPromise = $http.get('resources/json/part_numbers.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('PartsJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getPartsJson: function()
    {
      if (!data.length && !this.partsPromise) this.loadPartsJson();
      return data;
    }
  }
});