![](/img/trans.png)
[英]ionic3 how can i inject service/provider inside ErrorHandlerService
[英]How can i inject a service into a provider where the service is within a module passed into the providers module
如何將共享模塊中的服務注入到核心模塊中?
我在將PersistSettingsService注入LocalisationProvider時遇到麻煩。Localization在核心模塊中,而Persist在共享模塊中,這些都是這樣設置的。
const Core =
angular
.module('core', [Auth, Shared])
.constant('moment', moment)
.service('ModuleLazyLoaderService', ModuleLazyLoaderService)
.service('PermissionsService', PermissionsService)
.service('PersistSettingsService', PersistSettingsService)
.provider('ModuleLazyLoaderState', ModuleLazyLoaderStateProvider)
.provider('Localisation', LocalisationProvider)
.config(config)
.run(run);
我從共享中刪除了很多東西,因為有很多項目添加到共享中
const Shared = angular
.module('shared', [])
.service('PersistSettingsService', PersistSettingsService)
這導致
[$injector:modulerr] Failed to instantiate module app due to: Error: $injector:modulerr] Failed to instantiate module core due to: Error: [$injector:unpr] Unknown provider: PersistSettingsService
據我了解,共享應該包含在核心中,因此我應該能夠將其注入。我嘗試將其設置為提供程序,但這不能解決問題。
我有我的提供者類。
export default class LocalisationProvider {
$get() {
return {
getDateFormat: () => this.getDateFormat(),
getSetFormat: () => this.getSetFormat(),
getTimeFormat: () => this.getTimeFormat(),
setDateFormat: value => this.setDateFormat(value),
setTimeFormat: value => this.setTimeFormat(value)
};
}
constructor(PersistSettingsService) {
'ngInject';
this.persistSettingsService = PersistSettingsService;
}
}
我確保所有'ngInject'都存在,將不勝感激。
我已經創建了一個可復制的版本,但老實說,我不確定它們是否由於相同的原因而失敗。
您不能將服務注入提供程序本身。 將服務注入提供程序的$ get方法與將服務注入工廠一樣,但是不能直接將其注入提供程序功能。
但是我通過將提供者邏輯重構為服務,然后將其注入我的提供者$ get方法中來解決了這個問題,如下所示:
export default class LocalisationProvider {
$get(LocalisationController) {
'ngInject';
this.localisationController = LocalisationController;
this.getDateFormat = () => this.localisationController.getDateFormat();
return {
getDateFormat: () => this.getDateFormat(),
getSetFormat: () => this.localisationController.getSetFormat(),
getTimeFormat: () => this.localisationController.getSetFormat(),
setDateFormat: value => this.localisationController.setDateFormat(value),
setTimeFormat: value => this.localisationController.setTimeFormat(value)
};
}
}
getDateFormat既在get外部又在內部的原因是,提供程序在模塊加載階段運行,而$ get在實例化要提供的服務時運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.