Eric Mitjans
Eric Mitjans

Reputation: 2179

Adding custom headers to AngularJS app

I wonder if there's a way to add custom headers to my AngularJS app without having to add them to every single call.

So far an example from my calls look like this:

$http.get('http://api.discogs.com/artists/' + $scope.artist.id + '/releases?page=' +       $scope.nextPage + '&per_page=8').then(function(data2) {
    $scope.nextPage = $scope.nextPage + 1;
    if($scope.nextPage > data2.data.pagination.pages){
       $scope.morePages = false;
    }
    $scope.releases = $scope.releases.concat(data2.data.releases);
})
.finally(function(){
    $scope.loading = false;
}); 

I've observed in another question that somebody would include the headers like so:

$http({method: 'GET', url: 'http://localhost:3000/api/symbol/junk', 
       headers:{
         'Access-Control-Allow-Origin': '*',
         'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
         'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
         'X-Random-Shit':'123123123'
       }})
      .success(function(d){ console.log( "yay" ); })

But first, I wouldn't know how to integrate it in my call, and second I assume this would work for only one call, not for all of them.

Any tips?

Thanks!

Upvotes: 0

Views: 156

Answers (1)

ms87
ms87

Reputation: 17492

To make that call with your approach:

var makeCall = function(artistId,etc...,callBackFunc){
 var config={method: 'GET',
          url: 'http://api.discogs.com/artists/', 
          params:{artistId:artistId,etc....}
          headers:{
         'Access-Control-Allow-Origin': '*',
         'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
         'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
         'X-Random-Shit':'123123123'
 }};
 $http(config).then(function(data){
    callBackFunc(data);
 })
}

And use it in your controller like this:

myService.makeCall(artistId, other parameters such as page no,.....,function(data2){
$scope.nextPage = $scope.nextPage + 1;
    if($scope.nextPage > data2.data.pagination.pages){
       $scope.morePages = false;
    }
    $scope.releases = $scope.releases.concat(data2.data.releases);

})

And yes, that works for one request, you can use a $http interceptor to apply it to all requests.

Upvotes: 1

Related Questions