I was surprised that there is no exact answer to question:
What are methods forRoot/forChild made for?
For example in RouterModule:
Router.forRoot(routes)
I was surprised that there is no exact answer to question:
What are methods forRoot/forChild made for?
For example in RouterModule:
Router.forRoot(routes)
Usage notes
RouterModule can be imported multiple times: once per lazily-loaded bundle. Since the router deals with a global shared resource--location, we cannot have more than one router service active.
That is why there are two ways to create the module:
1. RouterModule.forRoot - forRoot creates a module that contains all the directives, the given routes, and the router service itself.
2. RouterModule.forChild - forChild creates a module that contains all the directives and the given routes, but does not include the router service..
RouterModule#forRoot
While RouterModule#forChild
The first is usually used to create the initial configuration for the Angular app and register the "base" routes while the second is usually used to configure "relative" routes.
Let's say we have an app with routes for:
You could use the mentioned methods like this:
app-routing.module.ts (this is a "real" app, routes differ)
Where the base routes
user/
andcompany/
are registered usingRouterModule#forRoot
user-routing.module.ts (this is a "real" app, routes differ)
And the relative routes to
user/
andcompany/
are registered usingRouterModule#forChild
And the same would go on for the Company children routes.
Use forRoot/forChild convention only for shared modules with providers that are going to be imported into both eager and lazy module modules
this one is a greate answer What is purpose of using forRoot in NgModule? can give extra information about this topic