How to retrieve response headers and set request headers using the strategy described in the tutorial.

152 views
Skip to first unread message

javier hector

unread,
Jul 11, 2013, 3:36:35 PM7/11/13
to ang...@googlegroups.com
Hi, All , I'm new to Angular and I want to know how to retrieve response headers and based on these values set request headers.

A use case for this should be set Conditional GET requests or Conditional PUT requests in a REST service.


For example

var MyApp = angular.module ('MyApp',['ngResource']);

MyApp.config(function($routeProvider, $locationProvider,$httpProvider) {
  $routeProvider
    .when('/', {controller: ListCtrl, templateUrl: '/partials/list.html'})
.when('/edit/:id', {controller: EditCtrl, templateUrl: '/partials/details.html'})
.when('/new', {controller: CreateCtrl, templateUrl: '/partials/details.html'})
    .otherwise({redirectTo: '/'});
   $locationProvider.html5Mode(true);
});

MyApp.factory('MyAppService', function($resource) {
  return $resource('/example/:id', {id: '@id'}, {update: {method: 'PUT'}});
  });
  
 
function EditCtrl ($scope, $location, $routeParams,MyAppService) {

 $scope.get = MyAppService.get({id: $routeParams.id}, function(data,headers) {
$scope.example = data.content;
$scope.ifmatch = headers().etag;
 });

 
  $scope.action = 'Update';
  $scope.save = function() {
    MyAppService.update({id: $routeParams.id},,$scope.example, function() {
      $location.path('/');
    })
  }
};

So suppose I want in the  the EditCtrl  set the if-match request header using the etag value sent from the server, if any.
I tried to do  send the {headers :{'if-match' : $scope.ifmatch}} as part of update call but it does not work.
  MyAppService.update({id: $routeParams.id}, {headers :{'if-match' : $scope.ifmatch}} ,$scope.example, function() {
What do you suggest to do in this scenario?

Thanks
/Javier
 

Eduardo Martins Barbosa

unread,
Oct 27, 2015, 1:41:48 PM10/27/15
to AngularJS
For this specific case, supposing your API returns a key etag along with the object you could define your service like this:

return $resource('/example/:id', {id: '@id'}, {
  update:
 {
    method: 'PUT',
    headers: {
      'If-Match': function(config) {
        return config.data.etag;
      }
    }
  }
});

This works for PUT and PATCH methods. If you also need it to work for DELETE, checkout this fork: https://github.com/eduardomb/ng-resource-etag
Reply all
Reply to author
Forward
0 new messages