Modules - deependhamecha/angular GitHub Wiki

You cannot declare same Component in different modules but you can provide services in different modules.

The forRoot() pattern Generally, you'll only need providedIn for providing services and forRoot()/forChild() for routing. However, understanding how forRoot() works to make sure a service is a singleton will inform your development at a deeper level.

If a module defines both providers and declarations (components, directives, pipes), then loading the module in multiple feature modules would duplicate the registration of the service. This could result in multiple service instances and the service would no longer behave as a singleton.

There are multiple ways to prevent this:

Use the providedIn syntax instead of registering the service in the module. Separate your services into their own module. Define forRoot() and forChild() methods in the module. Note: There are two example apps where you can see this scenario; the more advanced NgModules live example, which contains forRoot() and forChild() in the routing modules and the GreetingModule, and the simpler Lazy Loading live example. For an introductory explanation see the Lazy Loading Feature Modules guide.

Use forRoot() to separate providers from a module so you can import that module into the root module with providers and child modules without providers.

Create a static method forRoot() on the module. Place the providers into the forRoot() method. src/app/greeting/greeting.module.ts

static forRoot(config: UserServiceConfig): ModuleWithProviders {
  return {
    ngModule: GreetingModule,
    providers: [
      {provide: UserServiceConfig, useValue: config }
    ]
  };
}

forRoot() and the Router RouterModule provides the Router service, as well as router directives, such as RouterOutlet and routerLink. The root application module imports RouterModule so that the application has a Router and the root application components can access the router directives. Any feature modules must also import RouterModule so that their components can place router directives into their templates.

If the RouterModule didn’t have forRoot() then each feature module would instantiate a new Router instance, which would break the application as there can only be one Router. By using the forRoot() method, the root application module imports RouterModule.forRoot(...) and gets a Router, and all feature modules import RouterModule.forChild(...) which does not instantiate another Router.