[英]How do you properly configure a provider service in Angular.js
What is the best practices or patterns to config a provider inside a config
block like how $locationProvider
and $routeProvider
do? 像
$locationProvider
和$routeProvider
那样在config
块中配置提供程序的最佳实践或模式是什么?
As far as I know, only providers are configurable inside config
blocks. 据我所知,只有提供程序是可在
config
块内config
。
The following code block is how I want to do with my own custom provider. 以下代码块是我要如何使用自己的自定义提供程序。
.config([
'$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider
.html5Mode(true)
.hashPrefix('!');
$routeProvider.otherwise({
redirectTo: '/'
});
$httpProvider.defaults.withCredentials = true;
}
])
There is a very good explanations on providers, factories and services at the official docs . 官方文档中对提供者,工厂和服务有很好的解释。
In a nutshell, you should create a provider and expose whatever methods you need, besides the $get
method. 简而言之,除了
$get
方法之外,您还应该创建一个提供程序并公开所需的任何方法。 Upon the config call, you can call any other method you have, and when the system inject the dependency, it's going to call the $get
method. 在config调用后,您可以调用您拥有的任何其他方法,并且当系统注入依赖项时,它将调用
$get
方法。
Assembled a simple Plnkr here , but that's how it's goes: 在这里组装了一个简单的Plnkr ,但是事情就是这样的:
1. The provider 1.提供者
app.provider('myService', function() {
var configuredValue;
this.setValue = function(val) {
configuredValue = val;
};
this.$get = function() {
return {
valueSettedByTheConfig: configuredValue
};
};
});
Here you created the provider for the myService
service, exposing a setValue
configuration method, as in $locationProvider.html5Mode
or $routeProvider.otherwise
. 在这里,您为
myService
服务创建了提供程序,并公开了setValue
配置方法,如$locationProvider.html5Mode
或$routeProvider.otherwise
。
2. The configuration moment 2.配置时刻
app.config(function(myServiceProvider) {
myServiceProvider.setValue('my configured value');
});
Here you configure you module, before it gets used, by calling the exposed setValue
method. 在这里,您可以通过调用公开的
setValue
方法来配置模块,然后再使用它。
Notice that we inject the provider ( myService*Provider*
), for during configuration phase, you can only inject providers, not services. 请注意,我们注入了提供程序(
myService*Provider*
),因为在配置阶段,您只能注入提供程序,而不能注入服务。
3. The usage 3.用法
app.controller('MainCtrl', function($scope, myService) {
$scope.name = myService.valueSettedByTheConfig;
});
And finally here you simply inject the service and Angular is going to call the provider's $get
method to generate the instance, after the config phase. 最后,在这里您只需注入服务,并且在配置阶段之后,Angular将调用提供程序的
$get
方法来生成实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.