Using angular-cache in the app.config() - angularjs

I am attempting to use angular-cache in the app.config section of my angular application as shown in this JSFiddle - http://jsfiddle.net/0b1jgwoj/
.config(function (componentFactoryProvider, Config, RestangularProvider, DSCacheFactory, $q) {
componentFactoryProvider.setViewPath(function (componentSnakeName, componentName) {
return 'components/' + componentSnakeName + '/' + componentSnakeName + '.html';
})
RestangularProvider.setBaseUrl(Config.API.path);
RestangularProvider.setRequestSuffix('.json');
var appCache = DSCacheFactory('appCache', {
maxAge: 3600000,
deleteOnExpire: 'aggressive',
storageMode: 'localStorage', // This cache will sync itself with `localStorage`.
onExpire: function (key, value) {
//Todo: implement logic to get data from server be it a collection or single object
}
});
//Intercept the Get Request and check for value in cache. If found cancel Get Request, if not continue get Request.
RestangularProvider.addFullRequestInterceptor(function (element, operation, what, url, headers, params, httpConfig) {
if(operation === 'get') {
debugger;
//Check the cache to see if the resource is already cached
var data = appCache.get(url);
//If cache object does exist, return it
if (data !== undefined) {
angular.extend(element, data);
var defer = $q.defer();
httpConfig.timeOut = defer.promise;
defer.resolve();
return {
headers: headers,
params: params,
element: element,
httpConfig: httpConfig
};
}
}
});
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response) {
//Cache the response from a get method
if(operation === 'get') {
debugger;
appCache.remove(url);
appCache.put(url, data);
}
//Unvalidate the cache when a 'put', 'post' and 'delete' is performed to update the cached version.
if (operation === 'put' || operation === 'post' || operation === 'delete') {
appCache.destroy();
}
return response;
});
})
Two errors arise (1) $q is not defined even though I have put it inside the DI list (2) DSCacheFactory is returning an Unknown Provider Error
Any ideas on how to solve these problems as it is important that this logic remains in .config() section since the restangular 'addFullRequestInterceptor' doesn't cancel the request in any other services but only the config section.
Thanks

Fixed the problem. Had to put the logic in the .run method as stated in this document https://github.com/mgonto/restangular#how-to-configure-them-globally

Related

Cancelling pendingRequests is not working for angularJS 1.7.2 version

I am trying to cancel pending api calls when the same api's are called again. I have dropdown onChange of which I am making my api call, here api call taking a lot of time to return data so i am cancelling all previous calls which are in pendingRequest array and keeping only the latest triggered call. please go through my code below
in my controller
angular.forEach($http.pendingRequests,function(r){
console.log(r.contractId);
if (r.contractId && r.contractId !== selectedContract) {
r.cancel.resolve('cancelled');
}
});
Here I am checking if the pending request is latest or not, by comparing current selected contract with pendingRequest array.
This is how I have written my service
getDashboardData:function(selectedContract) {
var deferred = $q.defer();
var cancel = $q.defer();
$rootScope.loaderOn=true;
var url = 'my_url_here';
$http.get(url, {
ignoreLoadingBar: true,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
cancel:cancel, //this is of type $q.defer();
contractId:selectedContract // here i assigned contrract id just to delete all pending api's other than current
}).then(function(data){
deferred.resolve(data.data);
$rootScope.loaderOn=false;
},function(error){
console.log(error);
return deferred.reject(err);
});
return deferred.promise;
}
I want to cancel or reject pending api calls. Any help will be appreciated thank you. Let me know if any other info required. Please correct me here.
I referred $http and doubt if cancel property exist in config object of $http.get function. You can use timeout property and use the value for cancelling the existing request.
I have replaced cancel property with timeout.
I hope below code helps.
// Declare the below objects in service level not inside getDashboardData function
var deferredObj = '';
var existingRequest = '';
getDashboardData: function(selectedContract) {
var deferred = $q.defer();
// Below condition will check to cancel the existing request
if (existingRequest) {
existingRequest = '';
deferredObj.resolve();
deferredObj = '';
} else {
deferredObj = $q.defer();
}
$rootScope.loaderOn=true;
var url = 'my_url_here';
existingRequest = $http.get(url, {
ignoreLoadingBar: true,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
**timeout : deferredObj.promise**, //this is of type $q.defer();
contractId:selectedContract // here i assigned contrract id just to delete all pending api's other than current
}).then(function(data){
deferred.resolve(data.data);
$rootScope.loaderOn=false;
},function(error){
console.log(error);
return deferred.reject(err);
});
return deferred.promise;
}
const request = new Map() // put this outside the main function
getDashboardData() { // call this on change
const url = 'my_url_here'; // value should be constant
const oldRequest = request.get(url) // get the last promise request
oldRequest.reject && oldRequest.reject('old request') // cancel's the last promise request
// last promise request successCallback won't be called since the promise is already rejected
$q((resolve, reject) => { // creates a new promise
request.set(url, { resolve, reject }) // store resolve, reject
return $http.get(url) // create api request
})
.then(successCallback) // on request success
.catch(rejectedOrErrorCallaback)
}
you can re implement it to something like this.
btw as per documentation. $http.pendingRequests is primarily meant to be used for debugging purposes. so i think that's a flag to stay away from using

Promise Chains in angularjs

I am uploading attachments using rest api in SharePoint 2013,for this I need to call upload attachment method on synchronous.
Because If I call upload attachment method asynchronous I am getting 409 conflict error.
How to chain promise objects in for loop.i.e I want to call second attachment method in first attachment success and so on..
Please help me in best approach of chaining of promises in for loop.
Common method for saving attachments:
var saveFileAngularJS = function (file, url) {
var deferred = $q.defer();
getFileBuffer(file).then(function (fileArrBuffer) {
$http({
method: 'POST',
url: baseUrl + url,
headers: {
'Accept': 'application/json;odata=verbose',
'Content-Type': undefined,
'X-RequestDigest': jQuery("#__REQUESTDIGEST").val()
},
data: new Uint8Array(fileArrBuffer),
transformRequest: []
}).then(function successCallback(data) {
deferred.resolve(data);
alert('Successfully saved.', data);
}, function errorCallback(error) {
deferred.reject(error);
alert('Failed to save!!!.', error);
});
});
return deferred.promise;
};
Method calling :
for (var i = 0; i < $scope.files.length; i++) {
var file = $scope.files[i]._file;
var response = lssDealService.insertAttachment(transactionId, file);
}
var insertAttachment = function (dealId, file) {
var attachmentUrl = listEndPoint + "/GetByTitle('TransactionList')/GetItemById(" + dealId + ")/AttachmentFiles/add(FileName='" + file.name + "')";
return baseService.saveFile(file, attachmentUrl);
};
Insert attachment will call SaveFile method.
I want to run this for loop sequentially, once the loop has been completed I need to process all promises and display success message to user.
Please help me to writing the chaining promises in effective way.
Lets say you have the attachements as an array,
function uploadMyAttachements() {
return myAttachements.reduce(function(promise, attachment) {
return promise.then(function () {
return upload(attachment);
})
.then(function(result) {
console.log('RESULT FOR LAST UPLOAD', result);
});
}, Promise.resolve());
}
function upload(attachment) {
//upload the attachment to sharepoint
//and return a promise here
}
uploadMyAttachements().catch(function(err) {
//if anything in the promise chain fails
//it stops then and there and CATCHED here
});
Now whats happening here, using the Array.reduce, we create a chain of promises like shown below
upload(0).then(handleResult_0).upload(1).then(handleResult_1)....
and it execute one by one as you expected
Throwing my 2 pennies:
$scope.attachments = []; //modified via binding.
function uploadAttachments(){
//Reduce the files array into a promise array with the uploadOne method
//then return the promise when every promise has been resolved or one has rejected.
return $q.all($scope.attachments.reduce(uploadOne, []));
}
function uploadOne(file){
//Upload one, return promise. Use $http or $resource.
}
//Note - a more advanced way of doing this would be to send the files as batch (one
//$http post) as FormData. There are some good wrappers for angular.
$scope.upload = function(){
uploadAttachments().then(function(results){
//Array of results
}).catch(function(e){
//Error handler
});
}

AngularJS $http.get cache not working

After next(Route) to other page, come back it still call back the link.
How to cache JSON data from http call to optimize performance?
Try some solution but not working
$http.get(url, { cache: true}).success(...);
Any better solution to this?
Better way is to make CacheFactory as :-
var cache = $cacheFactory('myCache');
var data = cache.get(anyKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(anyKey, data);
});
}
You can also use angular-data directive for caching. It allows you to specify where caching : local storage / session / memory, and you can set the time you want to keep your requests in cache.
http://angular-data.pseudobry.com/documentation/guide/angular-cache/index
To initialize the cache, add this code in a app.run() function :
DSCacheFactory('defaultCache', {
maxAge: 900000, // Items added to this cache expire after 15 minutes.
cacheFlushInterval: 6000000, // This cache will clear itself every hour.
deleteOnExpire: 'aggressive', // Items will be deleted from this cache right when they expire.
storageMode:'memory' // [default: memory] sessionStorage, localStorage
});
$http.defaults.cache = DSCacheFactory.get('defaultCache');
And then use it in your code like you did :
$http.get(url, { cache: true}).success(...);
I recommend to you download angular-cache! It is a very useful replacement for Angular's $cacheFactory
Inside a .run() block, define your cache:
.run(function (DSCacheFactory) {
DSCacheFactory("dataCache", {
storageMode: "localStorage",
maxAge: 720000, // time in milliseconds
deleteOnExpire: "aggressive"
});
}
Then inside your Service you can manage how to use your data, get it from Cache when it expires, make a new call and refresh data.
(function (){
'use strict';
app.factory('DataService', ['$http','$q','DSCacheFactory',DataService]);
function DataService($http, $q,DSCacheFactory){
self.dataCache= DSCacheFactory.get("dataCache");
self.dataCache.setOptions({
onExpire: function(key,value){
getData()
.then(function(){
console.log("Data Cache was automatically refreshed", new Date());
}, function(){
console.log("Error getting data. Putting expired info again", new Date());
// This line of code will be used if we want to refresh data from cache when it expires
self.dealerListCache.put(key,value);
});
}
});
function getData(){
var deferred = $q.defer(),
cacheKey = "myData",
dataFromHttpCall = self.dataCache.get(cacheKey);
if(dataFromHttpCall){
console.log("Found in cache");
deferred.resolve(dealersList);
} else {
$http.get('/api/dataSource')
.success(function (data) {
console.log("Received data via HTTP");
self.dataCache.put(cacheKey, data);
deferred.resolve(data);
})
.error(function () {
console.log('Error while calling the service');
deferred.reject();
});
}
return deferred.promise;
}
};
})();
That´s all!

Implementing sockets into $http in angularjs

I implemented Primus (Sockets) on my Server and would like to access it via the client, which uses AngularJS. I would like to be able to still use libraries like Restangular or the $resource from Angular. So IMHO the best way to achieve this is to extend the $http service, which is used by most libraries as the basis.
I would like this new service to be able to gracefully fall back to the normal $http, when there is no socket connection available.
In Pseudocode:
socketHttpService = function(config) {
if(socketEnabled) {
var message = buildMessageFromConfig();
primus.write(message);
return promise;
}
return $http(config);
}
Call it like you would $http
socketHttpService({method: 'GET', url: '/someUrl'}).then(function() {
// do whatever
});
My question is, how can i replace the standard $http service with this newly created one? Is there an elegant way, while still retaining the default $http behaviour?
In the meantime, I found a solution to the problem
.config(function($provide) {
$provide.decorator('$httpBackend', function($delegate, $q, $log, SocketService) {
// do not blast mock $httpBackend if it exists
if (angular.isDefined(angular.mock)) {
return $delegate;
}
var httpBackendSocket = function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
if(SocketService.isOpen) {
console.log('open');
method = method.toLowerCase();
// we only know get, post, put, delete
if(method === 'get' || method === 'post' || method === 'put' || method === 'delete') {
// we can not handle the authentication links via sockets, so exclude them
if( url.substring( 0, '/api/v1/currentuser'.length ) !== '/api/v1/currentuser' &&
!angular.equals(url, '/api/v1/login') &&
!angular.equals(url, '/api/v1/logout') &&
!angular.equals(url, '/api/v1/session') ) {
var promise = SocketService.writeRest(method, url, post || {});
return promise.then(function promiseSuccess(response) {
return callback(response.status, response.data, response.headers, '');
}, function promiseError(response) {
// is caught via http handlers
// LATER: If error, retry with $httpBackend ($delegate)
return callback(response.status, response.data, response.headers, '');
});
}
}
}
return $delegate(method, url, post, callback, headers, timeout, withCredentials, responseType);
}
return httpBackendSocket;
});
})
Why? Because it feels like 5 times faster than http, because there is a standing connection and I am not losing any of the realtime options. It's like a cherry on top.
Kind Regards

Cancelling a request with a $http interceptor?

I'm trying to figure out if it is possible to use a $http interceptor to cancel a request before it even happens.
There is a button that triggers a request but if the user double-clicks it I do not want the same request to get triggered twice.
Now, I realize that there's several ways to solve this, and we do already have a working solution where we wrap $http in a service that keeps track of requests that are currently pending and simply ignores new requests with the same method, url and data.
Basically this is the behaviour I am trying to do with an interceptor:
factory('httpService', ['$http', function($http) {
var pendingCalls = {};
var createKey = function(url, data, method) {
return method + url + JSON.stringify(data);
};
var send = function(url, data, method) {
var key = createKey(url, data, method);
if (pendingCalls[key]) {
return pendingCalls[key];
}
var promise = $http({
method: method,
url: url,
data: data
});
pendingCalls[key] = promise;
promise.finally(function() {
delete pendingCalls[key];
});
return promise;
};
return {
post: function(url, data) {
return send(url, data, 'POST');
}
}
}])
When I look at the API for $http interceptors it does not seem to be a way to achieve this. I have access to the config object but that's about it.
Am I attempting to step outside the boundaries of what interceptors can be used for here or is there a way to do it?
according to $http documentation, you can return your own config from request interceptor.
try something like this:
config(function($httpProvider) {
var cache = {};
$httpProvider.interceptors.push(function() {
return {
response : function(config) {
var key = createKey(config);
var cached = cache[key];
return cached ? cached : cached[key];
}
}
});
}
Very old question, but I'll give a shot to handle this situation.
If I understood correctly, you are trying to:
1 - Start a request and register something to refer back to it;
2 - If another request takes place, to the same endpoint, you want to retrieve that first reference and drop the request in it.
This might be handled by a request timeout in the $http config object. On the interceptor, you can verify it there's one registered on the current request, if not, you can setup one, keep a reference to it and handle if afterwards:
function DropoutInterceptor($injector) {
var $q = $q || $injector.get('$q');
var dropouts = {};
return {
'request': function(config) {
// I'm using the request's URL here to make
// this reference, but this can be bad for
// some situations.
if (dropouts.hasOwnProperty(config.url)) {
// Drop the request
dropouts[config.url].resolve();
}
dropouts[config.url] = $q.defer();
// If the request already have one timeout
// defined, keep it, othwerwise, set up ours.
config.timeout = config.timeout || dropouts[config.url];
return config;
},
'requestError': function(reason) {
delete dropouts[reason.config.url];
return $q.reject(reason);
},
'response': function(response) {
delete dropouts[response.config.url];
return response;
},
'responseError': function(reason) {
delete dropouts[reason.config.url];
return $q.reject(reason);
}
};
}

Resources