【问题标题】:How can i inject a service into a provider where the service is within a module passed into the providers module我如何将服务注入提供者,其中服务位于传递给提供者模块的模块中
【发布时间】:2018-09-05 20:39:39
【问题描述】:

如何将共享模块中的服务注入核心模块?

我在将 PersistSettingsService 注入 LocalisationProvider 时遇到问题 本地化位于核心模块中,而 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

据我了解,shared 应该包含在核心中,因此我应该能够将其注入。我尝试将其设置为提供程序,但这并没有解决问题。

我有我的 Provider 课程。

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”都存在,我们将不胜感激。

我创建了一个可重现的版本,但老实说,我不确定它们是否因相同的原因而失败。

https://jsfiddle.net/panf8L6s/17/

【问题讨论】:

    标签: javascript angularjs dependency-injection


    【解决方案1】:

    您不能将服务注入提供程序本身。将服务注入提供者的 $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 在实例化您提供的服务时运行。

    【讨论】:

      猜你喜欢
      • 2020-07-18
      • 2020-06-23
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2019-07-16
      相关资源
      最近更新 更多