Igor Simic
3 years ago

Angular - access response headers in resolve response


How to access headers in ui router response?
Sometimes is needed to access some headers response values on  route change, to achieve that we will be attaching complete headers (or some part of it)
 to resolve response which will be passed to controller. 
In our case we are using $promise to return modified response:

$stateProvider
.state('tag',{
	url:'/tag/{slug:SlashFix}',
	cache:false,
	resolve:{
		resContent: ['$stateParams','$resource',function($stateParams,$resource){
  

				var getContent = $resource('http://link.to/your-resource');

				return getContent.query({}, function(response, responseHeaders){
				   
				  	// get single header element
				  	response.x_wp_total=responseHeaders('Content-Type');
				  	
				  	// get all headers
				  	response.responseHeaders = responseHeaders(); 
				  	return response;

				}).$promise.then(function(response) {

			                return response; 

				});

				

		}],
		 
	},

         views: {
	         'bodyview': {

	         controller: 'ViewCtrl',
		 templateUrl: 'templates/your_template.templ.html',
			          }
         }
	 

})

and now it can be accessed in conroller:
app.controller('ViewCtrl',['$scope','resContent','sidebarContent',function($scope,resContent,sidebarContent){

		// get all headers
                console.log(resContent.responseHeaders)

	}]);