我想知道我在性能和最佳实践方面的决定,因为这看起来像代码味道和性能影响。
http.get
每个过滤器以进行服务呼叫代码架构:
html
{{ data.whatever | myfilter }}
过滤
.filter .. calls service with the specific code e.g. "DL"
服务
var airportCodeService = function ($http, $q) {
var serviceBase = '../apps/temp/Api_Responses/',
factory = {};
factory.getAirlineFromCarrierId = function (code) {
return $http.get(serviceBase + 'Airlines.json').then(function (results) {
return findAirport(results.data, code);
});
}
function findAirport(airportList, code) {
var airLen = airportList.airlines.length;
var res = "";
for (var i = 0; i < airLen; i++) {
var item = airportList.airlines[i];
if (item.carrierId == code) {
res = item.airline;
break;
}
}
//console.log(res);
return res;
}
似乎我应该坚持使用json数据而不是$ http.get调用每个过滤器请求等。???
答案 0 :(得分:2)
如果json是静态的,则没有理由重复请求它。你是对的,这对性能来说太糟糕了!
最直接的解决方法是在airportCodeService
初始化时请求数据一次,并保存对该承诺的引用。
var airportCodeService = function($http, $q) {
var serviceBase = '../apps/temp/Api_Responses/',
factory = {};
//Request the data once at service startup
var airlinePromise = $http.get(serviceBase + 'Airlines.json');
factory.getAirlineFromCarrierId = function(code) {
//Reuse the same promise - it won't make another request!
return airlinePromise.then(function(results) {
return findAirport(results.data, code);
});
}
}