How to use .forRoot() within feature modules hierarchy

前端 未结 3 1363
遥遥无期
遥遥无期 2020-12-04 09:51

Can anyone please clarify to me how should I structure multiple nested feature modules hierarchy with .forRoot() calls?

For example what if I have modules like this:

3条回答
  •  隐瞒了意图╮
    2020-12-04 10:24

    Generally forRoot is used to add application/singleton services.

    @NgModule({
      providers: [ /* DONT ADD HERE */ ]
    })
    class SharedModule {
      static forRoot() {
        return {
          ngModule: SharedModule,
          providers: [ AuthService ]
        }
      }
    }
    

    The reasoning is that if you add the AuthService to the providers in the @NgModule, it's possible for more than one to be created if you import the SharedModule into other modules.

    I'm not 100% clear on whether the service would be created when the SharedModule is imported into an eagerly loaded module, but the explanation that the docs mentioned was in regards to lazily loaded modules. When you lazily load a module, all the providers will get created.

    For this reason, we add a (by convention) forRoot method to signify that the method should only be called for the root (app) module, while for other module it should just be imported normally

    @NgModule({
      imports: [SharedModule]
    })
    class FeatureModule {}
    
    @NgModule({
      imports: [SharedModule.forRoot()]
    })
    class AppModule {}
    

提交回复
热议问题