我需要加载两个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();
AventosJsonLoaded
和PartsJsonLoaded
答案 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;
}
}
});