I want to disable cache on angular ui grid. How can I do it? It is not mentioned in the documentation or tutorials.
I already have tried this:
$(function () {
console.log("ready!"); //Disable Local Cache
$.ajaxSetup({ cache: false });
});
How are providing data to ui-grid? You have to disable caching in the place from where you getting the data. If you are using $http then you can pass the no-cache header along with the request.
E.g.
$http.get( 'url' , { headers: { 'Cache-Control' : 'no-cache' } } );
If you are using ajax then whatever you have commented in the question should work fine.
Related
I'm having to inline all resources into one file and this includes all the data that my application uses. With a gulp process, I've been able to create a $cacheFactory with all the data:
angular.module('app').run('$cacheFactory', '$http', function($cacheFactory, $http){
var $httpDefaultCache = $cacheFactory.get('$http');
$httpDefaultCache.put('/data/names.json',{...});
$httpDefaultCache.put('/data/places.json',{...});
});
My understanding of how to access this instead of making a call externally (file) may be incorrect.
I thought that by setting $httpProvider.defaults.cache = true, that my request to the endpoints of above would use the default cache.
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.cache = true;
}]);
Instead I get an error of
https://.../data/names.json 404 (Not Found)
As if it is looking within the the client and not in angular's cache. The type is also an xhr.
data.load(names, '/data/names.json');
...
function load(broadcastName, url, force){
if(!isLoaded[broadcastName] && !force){
console.log('Loading name data from', url);
// Make the http GET request
http({
method: 'GET',
url: url,
cache: true
}).then(function success(response){
console.log("response: ", response)
...
})
Had to create a custom http request that perfectly imitates angular $http service. It is used in several other applications we have, so I know it works. Only thing that has been added for this implenation is cache:true.
I've looked at several other questions that were similar, but I am still not understanding how it is working. How does using http default cache work? And is there something I should be aware of that I may be glossing over?
I hope this makes sense.
There's no special term for $http cache like '$httpDefaultCache'. It works like you expect it to work. You set either $httpProvider.defaults.cache or cache request option to true, and the response is retrieved from $http cache, which is available by default as $cacheFactory.get('$http').
Cache is just key/value storage. If request URL doesn't match a key completely, cache won't be used.
Here's an example how it works:
$cacheFactory.get('$http').put('/foo', 'foo');
$http({ url: '/foo', cache: true })
.then(result => {
$scope.foo = result.data;
})
.catch(result => console.error(result))
I am building an Ionic app, and trying to set custom headers for every GET request I do on the app.
This is the CustomHeaderController
angular.module('myHeader',[])
.controller('headerCtrl',['customHeader',function(customHeader){
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'text/html;odata=verbose',
"X-Request-from" : "{{vm.data.os}}" }};
$http.get('http://localhost:8100, config); }])
At the moment when I inspect the page, I do not get any custom header, just the default one.
Any clues? Appreciate it! Cheers.
You need to use interceptor in this case with every http request.
Interceptor Details
I am trying to do a an HTTP POST to a server.
The data I have to send is a json object.
The problem is that $http.post in angular override the method with options.
I can make this config
.config(['$httpProvider', function ($httpProvider) {
//Reset headers to avoid OPTIONS request (aka preflight)
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
}])
and changes from options to POST, but I can't set the content-type to "application/json", and I am getting a "415 Unsupported Media Type"
Thank you
$http.post in angular doesn't override the method with OPTIONS. It appear that you are trying to call api in different domain than the one your JS code come from. This is called Cross Domain. For such cases the browser performs preflight request with OPTIONS in order to see the returned headers. In your backend response you should add the header Access-Control-Allow-Origin: * for example. When the browser sees that header he performs the actual POST request.
More details here: https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
Hope this is helps!
Add
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
But note this will set the Content-Type header globally.
If you need to set the content-type per call, you should use $http.post like
$http.post("/foo/bar", requestData, {
headers: { 'Content-Type': 'application/json'},
transformRequest: transform
}).success(function(responseData) {
//do stuff with response
});
I am trying to cache the response with angularjs but its not happening .
code #1
var app = angular.module("jsonService", ["ngResource"]);
app.factory("JsonFactory", function($resource,$cacheFactory) {
var cache = $cacheFactory('JsonFactory');
var url = "myurl?domain=:tabUrl";
var data = cache.get(url);
if (data==undefined) {
var retObj = $resource(url, {}, {
list: {
method: "GET",
cache: true
}
});
data = retObj;
cache.put(url, data);
};
return cache.get(url);
});
code #2
var app = angular.module("jsonService", ["ngResource"]);
app.factory("JsonFactory", function($resource) {
var url = "myurl?domain=:tabUrl";
console.log(url);
var retObj = $resource(url, {}, {
list: {
method: "GET",
cache: true
}
});
return retObj;
});
after both the code i wrote . when looking in to dev tools there always goes a XHR request in Network tab.
obviously : date does not changes . ( that's the whole point of caching )
After reading some of your responses, I think that what you are asking, is why does the network tab show a 200 response from your server, while using angular caching.
There are two caches. The first cache is angular's cache. If you see an xhr request in the network tab at all, then that means angular has decided that the url does not exist in its cache, and has asked the browser for a copy of the resource. Furthermore, the browser has looked in it's own cache, and decided that the file in its cache does not exist, or is too old.
Angular's cache is not an offline cache. Every time you refresh the browser page, angular's caching mechanism is reset to empty.
Once you see a request in the network tab, angular has no say in the server response at all. If you're looking for a 304 response from the server, and the server is not providing one, then the problem exists within the server and browser communication, not the client javascript framework.
A 304 response means that the browser has found an old file in its cache and would like the server to validate it. The browser has provided a date, or an etag, and the server has validated the information provided as still valid.
A 200 response means that either the client did not provide any information for the server to validate, or that the information provided has failed validation.
Also, if you use the refresh button in the browser, the browser will send information to the server that is guaranteed to fail (max-age=0), so you will always get a 200 response on a page refresh.
According to the documentation for the version of angular that you are using, ngResource does not support caching yet.
http://code.angularjs.org/1.0.8/docs/api/ngResource.$resource
If you are unable to upgrade your angular version, you may have luck configuring the http service manually before you use $resource.
I'm not exactly sure of syntax, but something like this:
yourModule.run(function($http)
{
$http.cache=true;
});
$cacheFactory can help you cache the response. Try to implement the "JsonFactory" this way:
app.factory("JsonFactory",function($resource,$cacheFactory){
$cacheFactory("JsonFactory");
var url="myurl?domain=:tabUrl";
return{
getResponse:function(tabUrl){
var retObj=$resource(url,{},{list:{method:"GET",cache:true}});
var response=cache.get(tabUrl);
//if response is not cached
if(!response){
//send GET request to fetch response
response=retObj.list({tabUrl:tabUrl});
//add response to cache
cache.put(tabUrl,response);
}
return cache.get(tabUrl);
}
};
});
And use this service in controller:
app.controller("myCtrl",function($scope,$location,JsonFactory){
$scope.clickCount=0;
$scope.jsonpTest = function(){
$scope.result = JsonFactory.getResponse("myTab");
$scope.clickCount++;
}
});
HTML:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular-resource.js"></script>
<script src="js/ngResource.js"></script>
<body ng-app="app">
<div ng-controller="myCtrl">
<div>Clicked: {{clickCount}}</div>
<div>Response: {{result}}</div>
<input type="button" ng-click="jsonpTest()" value="JSONP"/>
</div>
</body>
Screenshot:
[EDIT] for html5 localStorage solution
JSBin Demo
.factory("JsonFactory",function($resource){
var url="ur/URL/:tabUrl";
var liveTime=60*1000; //1 min
var response = "";
return{
getResponse:function(tabUrl){
var retObj=$resource(url,{},{list:{method:"GET",cache:true}});
if(('localStorage' in window) && window.localStorage !== null){
//no cached data
if(!localStorage[tabUrl] || new Date().getTime()>localStorage[tabUrl+"_expires"]) {
console.log("no cache");
//send GET request to fetch response
response=retObj.list({tabUrl:tabUrl});
//add response to cache
localStorage[tabUrl] = response;
localStorage[tabUrl+"_expires"] = new Date().getTime()+liveTime;
}
//console.log(localStorage.tabUrl.expires+"..."+new Date().getTime());
return localStorage[tabUrl];
}
//client doesn't support local cache, send request to fetch response
response=retObj.list({tabUrl:tabUrl});
return response;
}
};
});
Hope this is helpful for you.
I'm using angular and angular-resource version 1.1.5 and I'm using a $resource to make a request to a REST service. But it seems like the custom headers is not appended to the request. My definition is as below. Is there anything I did wrong?
myApp.factory('User', function($resource) {
var User = $resource('http://localhost\\:7017/mydomain/users/jack', { }, {
get: {
method: 'GET',
isArray: false,
headers: {'X-Requested-By':'abc'}
}
});
return User;
});
Read this to see how to configure default headers in one place: http://docs.angularjs.org/api/ng.$http
EDIT:
Your header must be included in Access-Control-Allow-Headers header in response to the OPTIONS request, which is sent automatically prior to your GET request.
You can modify the default headers inside the $httpProvider.
the headers are an object and separated intocommon, patch, post and put
so if you want to change the default for all your requests, just do a
$httpProvider.defaults.headers.put['Content-Type'] = 'application/json';
You have to call get method by using its name, i.e User.get(callback)
It seems that custom headers do not get sent when get method is called with User.query(callback)