I use AngularJS to build Single Page App. I want the code AnggularJS section always check the auth situation, always send with the headers information [X-Access-Token] whenever there is a connection to take data to server. The belows is the code I used, but it might have problem somewhere because It does not work. I have to add data of header X-Access-Token by hands into function $http get, post. Do you have any experiences of AngularJS, pls help me! Thank you.
app.factory('myHttpResponseInterceptor',['$q','$location',function($q,$location){
return function (promise) {
var success = function (response) {
return response;
console.log(response);
};
var error = function (response) {
if (response.status == 401) {
//$state.go('signin');
}
return $q.reject(response);
};
return promise.then(success, error);
};
}]);
//Http Intercpetor to check auth failures for xhr requests
app.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('myHttpResponseInterceptor');
}]);
app.factory('api', function ($http, $cookieStore, flash, $state) {
return {
init: function (token) {
$http.defaults.headers.common['X-Access-Token'] = token || $cookieStore.get('token');
}
};
});
app.run(function (api) {
api.init();
});
app.controller('adminProCatController', function($scope, $rootScope, flash, $state, $http, $cookieStore) {
$http.get('api/v1/categories?image_size=50x50', {headers: {'X-Access-Token': $cookieStore.get('token')}}).success(function(data) {
$scope.categories = data;
});
});