[英]How do you properly configure a provider service in Angular.js
像$locationProvider
和$routeProvider
那樣在config
塊中配置提供程序的最佳實踐或模式是什么?
據我所知,只有提供程序是可在config
塊內config
。
以下代碼塊是我要如何使用自己的自定義提供程序。
.config([
'$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider
.html5Mode(true)
.hashPrefix('!');
$routeProvider.otherwise({
redirectTo: '/'
});
$httpProvider.defaults.withCredentials = true;
}
])
官方文檔中對提供者,工廠和服務有很好的解釋。
簡而言之,除了$get
方法之外,您還應該創建一個提供程序並公開所需的任何方法。 在config調用后,您可以調用您擁有的任何其他方法,並且當系統注入依賴項時,它將調用$get
方法。
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
方法來生成實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.