1

So I have the following controller where I inject a constant, APIKEY.

myApp.controller('JobsCtrl', ['$scope', 'Jobs', 'APIKEY', function($scope, Jobs, apiKey) {
  var promise = Jobs.query().$promise;
  // do more awesome programming
}

I want to pass the apiKey to the following service but can't figure out for the life of me how to do it.

myApp.factory('Jobs', ['$resource', function ($resource) {
  return $resource('/someurl/:id', {id:'@id'}, {
    query: { method: 'GET', headers: {'Authorization': apiKey} }
  });
}]);

Thanks!

1
  • inject it as dependency the same way you do with $resource Commented Oct 31, 2013 at 1:59

2 Answers 2

7

Wrap your Jobs $resource inside another function:

myApp.factory('Jobs', ['$resource', function ($resource) {
  return function(apiKey){
    return $resource('/someurl/:id', {id:'@id'}, {
      query: { method: 'GET', headers: {'Authorization': apiKey} }
    });
  }
}]);

myApp.controller('JobsCtrl', ['$scope', 'Jobs', 'APIKEY', function($scope, Jobs, apiKey) {
  var promise = Jobs('MY_KEY').query().$promise;
  // do more awesome programming
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Stewie but surely someone can just view the source code on the webpage and view the APIKey in the source file? Then use the APIKey to gain access to the API endpoints
2

You can also take a look at the provide service API.

$provide.constant('APIKEY', 'theHash');

and then inject it into the controllers and services (for instance, when you create the service and inject dependencies into it).

1 Comment

fairly apparent in OP question that he's already registered the apiKey and is already using dependency injection for it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.