简体   繁体   English

Angular 6 Dependency Injection工厂服务不是单例

[英]Angular 6 Dependency Injection factory services are not being singleton

I have two modules AppModule and lazyLoadModule. 我有两个模块AppModule和lazyLoadModule。 where I am lazy loading lazyLoadModule from Appmodule. 在这里我懒于从Appmodule加载lazyLoadModule。 I want to share my providers with lazy loaded module refer . 我想共享我的提供者与延迟加载的模块refer I have created a SharedProviderModule as follows and imported in AppModule using SharedProviderModule.forRoot(): 我已经创建了一个SharedProviderModule,如下所示,并使用SharedProviderModule.forRoot()导入了AppModule:

import { NgModule, APP_INITIALIZER, ModuleWithProviders  } from '@angular/core';
import { CounterService } from './counter.service';
@NgModule({
})
export class SharedProviderModule {
    static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedProviderModule ,
      providers: [ CounterService 
      {
        provide: APP_INITIALIZER,
        useFactory: appConfigFactory,
        deps: [CounterService],
        multi: true
      },
]
    }
  }
}

As per the reference blog providers should have single instance for both modules, but right now for lazy loaded module new instance of provider is getting initiated. 根据参考,博客提供程序应为两个模块都具有单个实例,但是现在对于延迟加载的模块,将启动提供程序的新实例。 I am overriding some value using factory provider in SharedProviderModule which are not reflected in lazy loaded module. 我在SharedProviderModule中使用工厂提供程序覆盖了一些值,这些值未反映在延迟加载的模块中。 Is it something I forgot to do? 是我忘了做的事吗?

Your lazy loaded module will automatically have access to all providers registered in the app. 您的延迟加载模块将自动访问该应用程序中注册的所有提供商。 When your lazy loaded module imports a module with forRoot it actually registers those providers AGAIN, causing your issue. 当您的延迟加载模块使用forRoot导入模块时,它将实际上再次注册那些提供程序,从而导致您的问题。

You should never have a shared module containing providers, unless you don't want them to be singletons. 永远不要有一个包含提供程序的共享模块,除非您不希望它们成为单例。 If both your AppModule and lazy loaded module require a provider then register or import it in your AppModule and it will be available everywhere. 如果您的AppModule和延迟加载的模块都需要提供程序,则在AppModule注册或导入它,它将随处可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM