4
我正在嘗試使用ngResource來查詢REST API。我需要在自定義標題中指定我的API密鑰。我已經試過了,像這樣:AngularJS ngResource不發送自定義標頭
angular.module('ApiService', ['ngResource'])
.factory('Api', ['$resource', function($resource) {
this.apiEndpoint = '';
this.apiKey = '';
return {
init: function(apiEndpoint, apiKey) {
this.apiEndpoint = apiEndpoint;
this.apiKey = apiKey;
},
get: function(collection) {
return $resource(this.apiEndpoint + 'api/1/' + collection, {},
{
get: {
method: 'JSONP',
headers: {'api_key': this.apiKey},
params: {callback: 'JSON_CALLBACK'}
}
}
).get();
}
};
}]);
然後我在我的控制器使用這樣的:當我檢查XHR
app.controller('MyCtrl', function ($scope, Api, ENV) {
Api.init(ENV.apiEndpoint, ENV.apiKey);
var widgets = Api.get('widgets');
});
我的自定義標題沒有設置。另外,爲什麼在最初的$resource:get()
方法之後我呼叫空的.get()
之前,XHR不會運行?
我也試圖設置標題中$httpResource
直接:
.config(function($httpProvider) {
$httpProvider.defaults.headers.get = {'api_key': 'abc123'};
})
,但是這仍然沒有設置自定義標題,當我檢查網絡請求。我錯過了什麼?
您使用JSONP作爲方法。 – zeroflagL
可能重複[如何更改angularjs $ http.jsonp的標頭](http://stackoverflow.com/questions/19603757/how-to-change-the-headers-for-angularjs-http-jsonp) – maxdec
@ maxdec我認爲你是對的。由於無論出於何種原因,在過去的24小時內都得到了一點關注,所以我會將其作爲答案並進行交流。 –