我試圖從GitHub倉庫中獲取國家列表,但沒有將所有信息存儲在JS或我自己的API中,因此我編寫了一次性服務來照顧這對我來說,並緩存在瀏覽器中的結果,以防他們再次需要。然而,我注意到我寫的方式,$http.get
被稱爲負載而不是服務注入到控制器 - 這意味着即使不需要瀏覽器請求所有國家的數據(例如,即使當用戶訪問國家頁面時AngularJS服務延遲API調用
由於服務只是返回一個承諾,所以我可以在控制器中調用countrylist.then(...)
。有沒有辦法保持這一點,但仍然延遲直到它的實際需要Github的請求之下
代碼:
angular.module('myModule')
.factory('countrylist', ['$http', 'growl', '$q', function ($http, growl, $q) {
var deferred = $q.defer();
var flagUrl = "https://raw.githubusercontent.com/hjnilsson/country-flags/master/png250px/{}.png";
$http.get('https://raw.githubusercontent.com/lukes/ISO-3166-Countries-with-Regional-Codes/master/slim-2/slim-2.json',
{cache: true})
.success(function (data) {
angular.forEach(data, function (item) {
item.flag = flagUrl.replace("{}", item['alpha-2'].toLowerCase());
});
deferred.resolve(data);
}).error(function (data) {
growl.warn("Error loading country data");
deferred.reject();
});
return deferred.promise;
}]);