向 angular 服务/工厂提供配置的最佳方式是什么。例如推送器 api 密钥?我想编写一个可跨多个推送帐户重用的模块。
提前致谢
只需创建另一个服务并将其作为依赖项传递。
angular.module('myApp', [])
.factory('ProviderConfigService', function() {
return {
apiKey: '...'
}
})
.factory('ProviderService', function(ProviderConfigService) {
return {
doSomethingWithApi: function() {
var apiKey = ProviderConfigService.apiKey
}
}
});
我通常只提供一个注入常量:Angular Documentation
这是一个代码示例:
angular
.module('myApp', [])
.constant('apiKey', 'abc12345')
.controller('myController', function($scope, apiKey) {
$scope.key = apiKey;
});
还有一个 JSFiddle(虽然这会注入到控制器中进行演示,但它同样适用于服务)。
与更庞大的服务相比,常量的一大好处是您可以将它们注入config
块中。