![](/img/trans.png)
[英]Load JSON content from a local file with http.get() in Angular 2
[英]Performance concern with static .json file getting called repeatedly from $http.get call with angular
我想知道我的性能和最佳實踐決策,因為這看起來像是代碼味道和性能問題。
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。
如果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);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.