在config
块中配置提供程序的最佳做法或模式是什么,例如$locationProvider
和$routeProvider
如何做?
据我所知,只有提供商可在config
块内配置。
以下代码块是我想要使用自己的自定义提供程序的方式。
.config([
'$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider
.html5Mode(true)
.hashPrefix('!');
$routeProvider.otherwise({
redirectTo: '/'
});
$httpProvider.defaults.withCredentials = true;
}
])
答案 0 :(得分:1)
official docs对提供商,工厂和服务有很好的解释。
简而言之,除了$get
方法之外,您应该创建一个提供程序并公开您需要的任何方法。在配置调用时,您可以调用任何其他方法,当系统注入依赖项时,它将调用$get
方法。
组装了一个simple Plnkr here,但事情就是如此:
<强> 1。提供者
app.provider('myService', function() {
var configuredValue;
this.setValue = function(val) {
configuredValue = val;
};
this.$get = function() {
return {
valueSettedByTheConfig: configuredValue
};
};
});
您在此处为myService
服务创建了提供商,公开了setValue
配置方法,如$locationProvider.html5Mode
或$routeProvider.otherwise
。
<强> 2。配置时刻
app.config(function(myServiceProvider) {
myServiceProvider.setValue('my configured value');
});
在此,您可以在使用之前通过调用公开的setValue
方法为您配置模块。
请注意,我们注入了提供程序(myService*Provider*
),在配置阶段,您只能注入提供程序,而不是服务。
第3。用法
app.controller('MainCtrl', function($scope, myService) {
$scope.name = myService.valueSettedByTheConfig;
});
最后,您只需注入服务,Angular将在配置阶段之后调用提供程序的$get
方法来生成实例。