pcnate
pcnate

Reputation: 1774

angular $http get all headers

TL;DR;

I want to get all headers from the $http service and display them to the page. I don't care if it is only a list of the keys or the key/value pairs.

What I want to do

  $http
    .get( '/data/?some=parameters&go=here' )
    .success( function( response, status, headers ) {
      $scope.headers = headers();
    });

This outputs correctly in the Chrome console if I console.log either headers() or $scope.headers.

Only thing that I can do that works

  $http
    .get( '/data/?some=parameters&go=here' )
    .success( function( response, status, headers ) {
      $scope.headers['cache-control']     = headers('cache-control');
      $scope.headers['connection']        = headers('connection');
      $scope.headers['content-type']      = headers('content-type');
      $scope.headers['date']              = headers('date');
      $scope.headers['expires']           = headers('expires');
      $scope.headers['keep-alive']        = headers('keep-alive');
      $scope.headers['pragma']            = headers('pragma');
      $scope.headers['server']            = headers('server');
      $scope.headers['transfer-encoding'] = headers('transfer-encoding');
      $scope.headers['x-powered-by']      = headers('x-powered-by');
      // etc....
    });

This actually works in code, but I have to manually tell it every header to expect.

Meanwhile in my view

<div class="row" ng-repeat="(key,value) in headers">
  <div class="col-xs-4 text-right">{{ key }}</div>
  <div class="col-xs-8 text-left">{{ value }}</div>
</div>

AngularJS v1.3.15 was hurt during the making of this question.

Upvotes: 0

Views: 1851

Answers (1)

smnbbrv
smnbbrv

Reputation: 24571

I don't know why and how angular produces the headers object, but the reason of this error is that the object has no hasOwnProperty() function, which is used by ng-repeat loop to avoid standard JS functions calls.

What I managed to do is simple copying of the properties in a newly created object to make it work:

$scope.headers = {}

var tmp = headers()

for (var key in tmp) {
  $scope.headers[key] = tmp[key]
}

See the plunker as an example.

Upvotes: 3

Related Questions