【发布时间】:2014-07-07 18:43:29
【问题描述】:
我正在尝试使用 ngResource 来查询 REST API。我需要在自定义标头中指定我的 API 密钥。我试过这样:
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();
}
};
}]);
然后我在我的控制器中使用它:
app.controller('MyCtrl', function ($scope, Api, ENV) {
Api.init(ENV.apiEndpoint, ENV.apiKey);
var widgets = Api.get('widgets');
});
当我检查 XHR 时,我的自定义标题没有设置。另外,为什么 XHR 不会运行,直到我在初始 $resource:get() 方法之后调用一个空的 .get()?
我也尝试直接在$httpResource 中设置标题:
.config(function($httpProvider) {
$httpProvider.defaults.headers.get = {'api_key': 'abc123'};
})
但是当我检查网络请求时,这仍然没有设置自定义标头。我错过了什么?
【问题讨论】:
-
你使用 JSONP 作为方法。
-
@maxdec 我认为你是对的。由于这在过去 24 小时内无论出于何种原因引起了一些关注,我将把它作为答案和交叉链接发布。
标签: angularjs ngresource