I am creating an application using AngularJS framework.
The Problem:
When I jump out of my application to a different domain or a page and then when I use history back button to get back to my app, I get back only JSON. The same situation happens when I jump out of my app browsing back in history, and then when I use forward button to go to my app, again I get only JSON back. Back/forward works fine within my app, it happens only when I go to different domain.
Why is that? I think it is related to caching some how, because when I do back/forward to my app, no request is send to the server.
You can see what I'm talking about if you go to this url - http://test.deving.cz/admin/prihlasit/. Then go back and then forward.
My setup:
My app is configured to use HTML5 history API. For an url that starts mydomain.com/admin/ I always return an index.hmtl containing angular. Then for every other url in my app two requests are send out. One for the template and one for the data (the JSON).
Example:
$routeProvider.when('/admin/page/', {controller: 'PageListCtrl', templateUrl: '/templates/page/list/', resolve: 'PageListCtrl.resolve'})
PageListCtrl:
angular.module('page').controller('PageListCtrl', ['$scope', 'data', function($scope, data) {
$scope.pages = data;
}]);
Resolve function:
resolve = {data:
function($http, $q){
var delay = $q.defer();
$http.get().success(function(data){
delay.resolve(data['data']);
});
return delay.promise;
}
}
How should I configure angular or my app to tell the browser not to cache the data and to always get the index.html and then let angular do the requests?
I got the same problem. While I found a workaround to this problem, I think there must exist a better solution. So if you have any more better solution please let me know.
The server side framework I'm using is Rails. So I add the following code
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
These lines will prevent browser to cache your request, and you can detect whether a request is a XHR to decide add the above lines or not.
In the comments Ajay beniwal suggested that to stop browser from caching, the url should be dynamic:
'/partials/indexpage.html?id=' + new Date().getTime()
So if I do something like this in my resolve function:
$http.get($location.path() + '?id=' + new Date().getTime())
the app and browsing in history works fine.
However I feel like monkey patching a serious problem. So if anyone has a better answer that actualy solves the cause to the problem feel free to answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With