Reputation: 852
I'm developing an AJAX-heavy application with AngularJS and need requests to not be re-made when the user clicks the back button on their browser. For example a set of data takes 2-3 seconds to load and then if the user navigates to another page and then clicks back the data has to be reloaded. Is there a way to prevent this - or alternatively a different way to design my app such that data persists through a session?
Upvotes: 4
Views: 7807
Reputation: 3165
If you're using ngResource for loading data from api then set the cache to true in actions as in described in documentation
cache – {boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
https://docs.angularjs.org/api/ngResource/service/$resource
Example:
this.service=$resource('www.example.com/api/v/stats',
{
callback: "JSON_CALLBACK"
}, {'foo': {'method': 'GET', 'cache': true}}
);
Loading data through this.service.foo() will cache the request and on back button, it will use the cached data instead of reloading it.
Upvotes: 1
Reputation: 1
In an app I'm currently developing, I use the $routeProvider
heavily for each of the modules.
I do something like:
$routeProvider.when(/someModule/page1Condition1, {templateUrl: 'page1.tpl.html', controller: 'page1Ctrl'});
$routeProvider.when(/someModule/page1Condition2, {templateUrl: 'page1.tpl.html', controller: 'page1Ctrl'});
Then, in the controller for page1
I do something like:
if($location.path()==='/someModule/page1Condition2){
// something that should be done only when Condition2 is true,
// for example, loading data using ajax
$http.get('somePath')
.success(function(data){
$scope.myData = angular.fromJson(data);
});
}
In this way, I have just one controller but conditionally fetch data using the url path as an information source. Think of it like something that wants to be as close as REST as possible, but is actually not REST.
It's important to mention that I also have several weird requirements imposed by my client, thus this is quite probably not the best way to solve this problem (it could even be an antipattern, although I like to think that is just a temporary hack).
Upvotes: 0
Reputation: 4552
I strongly suggest that you study more on the usage of routing with AngularJS
A nice and quick way to do so would be watching some of John's tutorials, starting with this one: https://egghead.io/lessons/angularjs-ng-view
Finally, what you are trying to accomplish is showed in this one: https://egghead.io/lessons/angularjs-route-life-cycle
Hope this helps.
Upvotes: 0