Angularjs 防止每次加载模板时调用angular factory
我正在使用AngularJS和AngularRouting。我有模板“home.html”和该模板的控制器“homeController”。此外,我还有一个工厂:Angularjs 防止每次加载模板时调用angular factory,angularjs,Angularjs,我正在使用AngularJS和AngularRouting。我有模板“home.html”和该模板的控制器“homeController”。此外,我还有一个工厂: app.factory('therapyService', function ($http) { return { getTherapies: function () { //return the promise directly. return $http.get('http://localhos
app.factory('therapyService', function ($http) {
return {
getTherapies: function () {
//return the promise directly.
return $http.get('http://localhost:8080/application/api/rest/therapy').then(function (result) {
//resolve the promise as the data
return result.data;
});
}
}
});
In controller:
therapyService.getTherapies().then(function (results) {
$scope.therapies = results;
...
}
问题是每当我点击那个页面时,那个http调用就会被再次调用。我希望它只在第一次加载页面时调用。如何执行?您可以通过将配置参数传递给
$http
调用来启用单个调用的缓存:
return $http.get('url', { cache: true }).then(...)
如果您发现大多数调用需要缓存,而很少需要取消缓存,那么您可以在应用程序的配置阶段默认为调用启用缓存:
var myApp = angular.module('myApp',[])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.cache = true;
}])
然后,通过传递
{cache:false}
可以显式禁用某些调用的缓存。我建议显式启用缓存。缓存是一种优化,如果您忘记在某个时候禁用它,默认情况下启用它可能会导致应用程序崩溃。@firstChild缓存将持续应用程序的生命周期。