向AngularJS app添加自定义标头

时间:2014-04-15 11:51:43

标签: angularjs http-headers custom-headers

我想知道是否有办法将自定义标头添加到我的AngularJS应用程序中,而无需将其添加到每个调用中。

到目前为止,我的电话示例如下:

$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;
}); 

我在另一个问题中观察到有人会像这样包含标题:

$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" ); })

但首先,我不知道如何将它集成到我的通话中,其次我认为这只适用于一个电话,而不适用于所有电话。

任何提示?

谢谢!

1 个答案:

答案 0 :(得分:1)

用您的方法拨打电话:

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);
 })
}

并在你的控制器中使用它:

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);

})

是的,这适用于一个请求,您可以使用$http拦截器将其应用于所有请求。

相关问题