【发布时间】:2014-07-26 01:58:50
【问题描述】:
这听起来像是一个非常简单/愚蠢的问题,但我需要问一下,因为我之前没有遇到过这种情况......好吧,我的 angularJS 应用程序中有一个服务。该服务目前包含 4 种方法,它们都执行 80% 相同的功能/代码,我希望提高效率。这是我的服务的样子(删除了很多代码):
.factory('townDataService', function ($http) {
var townList = {};
townList.getTownList = function () {
return $http({method: 'GET', url: '/api/country/cities'})
.then(function (response) {
// HERE WE FORMAT THE response as desired... that creates a returnArray
var returnArray = [];
// loop through the countries
var JsonData = response.data;
for (key in JsonData['countries']) {
// formatting code...
}
// end of repeated CODE
return returnArray; // this is array, we don't do any formatting here
});
};
townList.getCurrentTown = function (place) {
return $http({method: 'GET', url: '/api/country/cities'})
.then(function (response) {
// HERE WE FORMAT THE response as desired... that creates a returnArray
var returnArray = [];
// loop through the countries
var JsonData = response.data;
for (key in JsonData['countries']) {
// formatting code...
}
// end of repeated code
// now the format further / work with the returnArray...
for (var i = 0; i < returnArray.length; i++) {
// do stuff
}
return currentTown; // this is a string
});
};
townList.getCurrentCountry = function (place) {
return $http({method: 'GET', url: '/api/country/cities'})
.then(function (response) {
// HERE WE FORMAT THE response as desired... that creates a returnArray
var returnArray = [];
// loop through the countries
var JsonData = response.data;
for (key in JsonData['countries']) {
// formatting code...
}
// end of repeated code
// now the format further / work with the returnArray...
for (var i = 0; i < returnArray.length; i++) {
// do stuff
}
return currentCountry; // this is a string
});
};
return townList;
}
)
;
现在我在每个方法中重复相同的$http 'GET' 和相同的格式化代码(这是很多嵌套循环),然后返回对象数组或字符串。这远非有效!将这个功能放入它自己的函数中的最佳方法是什么,所以我们只调用一次 GET url,但仍然用每个方法返回一个 promise?我是否应该将 $http({method: 'GET', url: '/api/country/cities'}) 的结果设置为 var 并在必要时在格式化数据之前将其注入/传递到每个方法中?我应该使用某种$cacheFactory吗?
对不起,如果这是一个愚蠢的问题,如果我没有很好地解释自己,我将重新提出问题。
提前致谢。
【问题讨论】:
标签: javascript angularjs angularjs-service