1

我有两个需要加载的 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

4

1 回答 1

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;
    }
  }
});
于 2013-08-23T03:12:13.103 回答