This is the solution I use in my angular js application...I have 2 services that I use...one gets the form digest value, the other runs on a 24 minute interval on the $rootScope and continuously updates the FormDigestValue no matter how long someone is inactive (so they don't attempt to post when they come back and get an error). You then inject the $rootScope.formDigestValue into any POST calls in AJAX in the header for "X-RequestDigest" property. The formDigestIntervalService is started upon application loading (or in the routeing script if using angular routes) by calling:
//start the form digest service
formDigestIntervalService.startFormDigestInterval($rootScope);
These services sit in a globalModule
//The service that retreives the Form Digest Value
.service('formDigestService', function($http, $q){
//Define the headers
$http.defaults.headers.common.Accept = "application/json;odata=verbose";
$http.defaults.headers.post['Content-Type'] = 'application/json;odata=verbose';
//Define the service call
this.getFormDigest = function () {
//Fetch the Url
JSRequest.EnsureSetup();
var appweburl = decodeURIComponent(JSRequest.QueryString['SPAppWebUrl']);
var dfd = $q.defer();
//Http post to the context info rest service
$http.post(appweburl + "/_api/contextinfo", {
data: '',
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "text/xml"
}
}).success(function (data) {
//Resolve the FormDigestValue from the success callback.
console.log('X-DIGEST: ' + data.d.GetContextWebInformation.FormDigestValue);
dfd.resolve(data.d.GetContextWebInformation.FormDigestValue);
}).error(function () {
dfd.reject("error finding form digest");
});
return dfd.promise;
};
})
//The interval service that sets the Form Digest Value to the $rootScope.
//This service will be injected with the formDigestService
.service('formDigestIntervalService', ['formDigestService', function ($formDigestService) {
var self = this;
self.startFormDigestInterval = function ($rootScope) {
//Define a property on the rootScope called formRequestDigest
if (!$rootScope.formRequestDigest) {
$rootScope.formRequestDigest = "";
}
//Set the Form Digest Value to the $rootScope every 24 min
$formDigestService.getFormDigest().then(function (digest) {
$rootScope.formRequestDigest = digest;
setTimeout(function () {
self.startFormDigestInterval($rootScope);
}
, 1000000);
return false;
}, function (error) {
console.error("Error retrieving form digest value: ", error);
});
};
}])