Can lazy-loaded modules share the same instance of a service provided by their parent?

后端 未结 3 776
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 07:48

I\'ve just run into a problem with a lazy-loaded module where parent and child module both require the same service but create an instance each. The declaration is identical

3条回答
  •  迷失自我
    2020-11-28 08:44

    This should work but still I would suggest you to go with SharedModule concept which contains common services,pipes,directives and components.

    Shared/SharedModule

    import { NgModule,ModuleWithProviders } from '@angular/core';
    import { CommonModule }        from '@angular/common';
    
    import { MyService } from './my.service';
    
    @NgModule({
      imports:      [ CommonModule ],
      declarations: [],
      exports:      [ CommonModule ]
    })
    export class SharedModule {
      static forRoot(): ModuleWithProviders {
        return {
          ngModule: SharedModule,
          providers: [ MyService ]                       //<<<====here
        };
      }
    }
    

    AppModule

    import {SharedModule} from './shared/shared.module';
    ...
    @NgModule({
       imports:[ BrowserModule,SharedModule.forRoot()],  //<<<====here
       providers: []
    });
    

提交回复
热议问题