![](/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.