[英]How can I pass parameters in an Angular.js Controller to a Resource?
So I have the following controller where I inject a constant, APIKEY. 因此,我有以下控制器在其中注入常量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. 我想将apiKey传递给以下服务,但我一生都无法解决。
myApp.factory('Jobs', ['$resource', function ($resource) {
return $resource('/someurl/:id', {id:'@id'}, {
query: { method: 'GET', headers: {'Authorization': apiKey} }
});
}]);
Thanks! 谢谢!
Wrap your Jobs $resource inside another function: 将Jobs $ resource包装在另一个函数中:
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
}
You can also take a look at the provide service API . 您还可以查看提供服务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). 然后将其注入控制器和服务中(例如,当您创建服务并将依赖项注入其中时)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.