4

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 を調べたときに、カスタム ヘッダーが設定されていません。.get()また、最初の$resource:get()メソッドの後に空を呼び出すまで XHR が実行されないのはなぜですか?

$httpResourceまた、ヘッダーを直接設定しようとしました:

  .config(function($httpProvider) {
    $httpProvider.defaults.headers.get  = {'api_key': 'abc123'};
  })

しかし、ネットワーク要求を検査するときに、これでもカスタム ヘッダーが設定されません。私は何が欠けていますか?

4

1 に答える 1