How can i Prevent caching in angular? - angularjs

I want to prevent caching in angular.For that i set the cache property to
false.After doing this i request the same url .But didn't send that request
to my server.
Used code for preventing,
$http({
cache : false,
method: "GET",
url :"myurl";
}).success(function(data) {
}).error(function(data) {
});
And code used for remove cache,
var $httpDefaultCache = $cacheFactory.get('$http');
$httpDefaultCache.remove('myurl');
$http({
cache : false,
method: "GET",
url :"myurl";
}).success(function(data) {
}).error(function(data) {
});
can u help me?Please

You could pass the dummy parameter in the URL so that URL become an unique by adding data into it. Passing dummy parameter in params array will not harm the $http get call.
$http({
method: 'GET',
url: 'myurl',
params: { 'dummy': new Date().getTime() }
})
This will ensure caching will not be done for your url.
Best option would be disable caching on server side link here

Related

Angularjs: Use the json file based on user selection

I have multiple json files as my datasource. How to use $http.get() to get the correct json files based on the user selection ?
try something like this
// Simple GET request example:
var fileName = 'myFile.txt' //name coming from where you call this service
$http({
method: 'GET',
url: '/someUrl/'+fileName
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
the alternative if you are using an api
var fileName = 'myFile.txt'
$http({
url: url: '/someUrl',
method: "GET",
params: {fileName: fileName}
});

AngularJS HTTP GET request returning cached data

In my AngularJS app I am sending HTTP GET request as below.
MyService.HttpReq("testUrl", "GET", null);
HttpReq Method is defined in a service and implemented as below:
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: postData,
headers: {
'Content-Type': 'application/json',
}
}).success(function(response)
{
console.log("Success: "+JSON.stringify(response));
}).error(function(data, status)
{
console.error("Error");
});
}
First of all is this the right way of sending HTTP request in AngularJS?
The problem that I am facing is, some times I get cached data as response and HTTP request is not hitting the server. what can be the issue?
UPDATE
As per the comment and answer I have updated my HTTP request code as below, but still getting same issue.
this.HttpReq = function(URL, method, payload)
{
$http({
url: URL,
method: method,
cache: false,
data: payload,
headers: {
'Content-Type': 'application/json',
'Cache-Control' : 'no-cache'
}
}).
then(
function(response)
{
var data = response.data;
console.log("Success: "+JSON.stringify(data));
},
function(response)
{
var data = response.data || "Request failed";
var status = response.status;
console.error("Error: "+JSON.stringify(data));
}
);
}
IE Browsers will catch ajax get requests even if we add cache control headers to the response. Only way i found to solve the issue is to add some random parameter to the request. Please make sure the api have no problem even if you send extra parameters
MyService.HttpReq("testUrl?ts=" + Date.now(), "GET", null);
Just add cache: false attribute to config object.
https://docs.angularjs.org/api/ng/service/$http#caching
Also you can add header: 'Cache-Control' : 'no-cache'

Update $scope.variable value after POST

I am creating an simple TODO app using AngularJS, i POST the data to server when response comes, that response i want to store it existing variable and refresh the view. i.e
// This stores on page load, its working fine
var todos = $scope.todos = sever_passed_data;
but when i do,
$scope.$watch('todos', function () {
var request = $http({
method: "post",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: my_url,
data: $.param({todos_list: angular.toJson(todos)})
});
request.success(function(responce){
var todos = $scope.todos = responce;
});
}, true);
after this it gives me weird(it goes in infinite loop and posting data to server) output, i mean the responce doesn't stores in todos variable.
If you want to store the returned value of the HTTP POST in the $scope.todos variable, you should use response.data. response contains the entire HTTP response, including the response code, response headers, response body, etc.
Why are you declaring the local variable todos? It will go out of scope as soon as the function exits. just assign $scope.todos. Also, you might want to use then instead of success. Here's an example:
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: my_url,
data: $.param({todos_list: angular.toJson(todos)})
}).then(function(response) {
$scope.todos = response.data;
});

Set defaults header on AngularJS but don't use it on one specific request

For sending OAuth2 token I am setting up defaults header on AngularJS like this:
$http.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
This works great but I don't need this header (I get an error) for one specific request.
Is there a way of excluding defaults header when performing that request?
Thanks!
SOLVED
Thanks to Riron for getting me on a right path. Here's the answer:
$http({
method: 'GET',
url: 'http://.../',
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
delete headers['Authorization'];
return headers;
}
});
When you make your call with $http, you can override defaults headers by providing them directly in your request config:
$http({method: 'GET', url: '/someUrl', headers: {'Authorization' : 'NewValue'} }).success();
Otherwise you could transform your request using the transformRequest parameter, still in your $http config. See doc :
transformRequest – {function(data,headersGetter)|Array.<function(data, headersGetter)>} – transform
function or an array of such functions. The transform function takes
the http request body and headers and returns its transformed
(typically serialized) version.
This way you could delete an header for a single request before it's being send:
$http({method: 'GET',
url: '/someUrl',
transformRequest: function(data,headersGetter){ //Headers change here }
}).success();
For latecomers, whilst the solution might have worked - you actually shouldn't need to use transformRequest for this.
The Angular docs for the $http service actually have this exact situation covered:
To explicitly remove a header automatically added via
$httpProvider.defaults.headers on a per request basis, Use the headers
property, setting the desired header to undefined.
For example:
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: {
test: 'test'
}
}
$http(req).success(function(){...}).error(function(){...});
Angular 1.4.0 can no longer modify request headers using transformRequest:
If one needs to dynamically add / remove headers it should be done in
a header function, for example:
$http.get(url, {
headers: {
'X-MY_HEADER': function(config) {
return 'abcd'; //you've got access to a request config object to specify header value dynamically
}
}
})
While the $httpProvider can override $http the use of intereceptors are 1 way of handling this, I end up doing it this way
function getMyStuff(blah) {
var req = {
method: 'GET',
url: 'http://...',
headers: {
'Authorization': undefined
}
}
return $http(req)
.then(function(response) {
return response.data;
});
}

$resource invalidation in angularjs

I have this use case where I pass authToken to every request and this token changes everytime the person logins.
app.factory('Comment', function ($resource, localStorageService, $cacheFactory) {
return $resource('http://localhost:port/comments/:id', {"id":"#id", port:':9000'}, {
query: { method:'GET', isArray: true , headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
save: { method:'POST',headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
update: {method:'PUT' ,headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
delete : {method: 'DELETE',headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
get : { method: 'GET', headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}}
});
The behaviour I am seeing is that if the authToken changes for some reason the $resource keeps adding the previous authToken while sending the request. I am using the $http directly for login and for any commenting related stuff I am using $resource. Am I missing something?
After login I make sure that my localStorage has the newly created token but the request are using the previous authToken till I refresh the page after which it adds the correct header I know that the $resource uses some kind of caching and tried to remove the $http cache like this after loggin in.
$cacheFactory.get('$http').removeAll();
but didnt't help
It's because token is assigned once when factory code executes. Try this instead:
get : { method: 'GET', headers: {
'X-AUTH-TOKEN': function(){
return 'authToken=' + localStorageService.get("authToken");
}
}}

Resources