One day I asked my self if I could use the same route path for different modules or components.
Why would I need this feature?
In my experience, I found this feature very useful in the following scenarios.
You want to use the same path for all users but depending on the user type/privileges which component/module should you load.
You have different versions of your web app and according to the server configuration, environment configuration and/or http responses, you can decide which version of the module/component to load.
Probably there are more reasons to use this feature, but these two are the reasons that came to my mind right now.
Let’s set an imaginary scenario to show better this feature.
We have a library web app where the customers could see the books available to use:
On the other hand, we have the library manager, who can list and add the books available.
Both types of users use the same url:
http://localhost:4200/books
According to the user type (consumer or manager), we should decide what is the module that we need to load.
Like we have just said we have two modules:
- Manager module
- Consumer module
And we are going to add a third module: Book Handler Module.
This last one (Book Handler Module) is going to be responsible to determine which module should we load. How is going to do that? We are going to provide the ROUTES of the RouterModule using the useFactory provider of Angular.
As you can see, the method “configBookHandlerRoutes” is going to determine what module we should load asking the AuthService if the user is authorized.
The AuthService is just a service from where we get the role of the user (consumer or manager).
Let’s see the application running:
Yes!!! It’s works!!!!
We have a bug… In the login page if we change the answer value of “Are you the library manager?” after we had already navigated to the “/books” page, the application will only load the book page that had loaded the first time:
The method “configBookHandlerRoutes” used by the useFactory provider in the BookHandlerModule is only executed the first time we navigate to the “/books” path and after that, the Angular Router already knows which module needs to load:
How can we fix this bug?
If the value of “authorized$” (property loaded in the login page) changes, we have to delete the “/books” path in the Router and add it again. Because of that when we navigate again to the “/books” path, the method “configBookHandlerRoutes” used by the useFactory provider will be executed again:
Let’s see the application running after this change:
That’s all!!!
I hope this article would be helpful for you.
If you have any doubt please comment this article and as soon as I can I will answer you.
Here you have the code in github:
https://github.com/gquinteros93/same-path-for-different-modules
Top comments (0)