What is Routing Module In Angular
The AppRoutingModule is an Angular Module, which specifically defines the application Routes
- There are no directives, pipelines, or components in this module. Therefore, there is nothing to declare in the declaration array.
- Since there are no services included in this module, a providers array is likewise not required.
The Angular RouterModule is imported since it is required for the routing to function.
Since the routes are necessary for the RouterModule to function, they are supplied to it in the forRoot method.
If we have components, directives or pipes in our project, which we want to share through the entire project, the best way to do that is to register them inside the shared module file. Then, we need to register the shared module inside the app module.
For Servies: It's crucial to avoid registering services in a shared module that we want to use globally. Such services should be registered either in their own feature module or in the app module.
But, If we still need any service registered inside a shared module, the best way is to provide it through the static forRoot() method that returns the ModuleWithProviders interface:
In the case of routing, theRouterModule provides the Router service. Without forRoot / forChild, each feature module would create a new Router instance but there can only be one Router. By using the forRoot method, the root application module gets a Router, and all feature modules use forChild and do not instantiate another Router.
Since forRoot and forChild are just methods you can pass parameters when calling them. For the RouterModule you pass the value of an additional provider, the routes, and some options:
What about Lazy-loaded modules?
Lazy-loaded modules have their own injectors and this can lead to issues when trying to keep some provided service a singleton..
By importing modules through the ModuleWithProviders interface, you may resolve this. The only practical pattern to wrap this neatly is forRoot/forChild. Although it isn't officially a part of Angular, the Angular team used it as the answer for the RouterModule, and it's a good idea to tackle related issues using the same pattern.