Best Route Forward — Declarative Route Path Management in Angular Apps
The Angular Router module provides the routerLink
directive that takes a string or an array of path segments representing the address to which we want to navigate . For example:
For small applications with one or two pages, we can get away using this approach. But for large applications, which are heavily routed, where we can navigate to the same location from many places, it won’t hold water.
Let’s create a checklist of what we expect our solution to feature:
- We want to have a single source of truth for each path in the application.
- We want typings ⭐️
- We want to access Angular’s dependency injection to use core services such as feature flags service, etc.
- We don’t want to use relative links because, well, they are location-dependent.
To achieve the points mentioned above, we’ll create a service that’ll manage our application paths:
First, we define two interfaces for both path and query parameters. Next, we create a service that exposes resolvers which returns the absolute path of the route.
We use the createUrlTree
method, passing the commands and the queryParams
, and call the toString
method, which returns the full path.
Now, we can use our service anywhere, both with the routerLink
directive, and navigateByUrl
:
Another advantage of this approach is that we can look at one file and see all our application routes.
If, for some reason, you prefer to split it into multiple files, I recommend taking a look at one of my previous articles, and use Angular DI multi option:
🚀 In Case You Missed It
Here are a few of my open source projects:
- Akita: State Management Tailored-Made for JS Applications
- Spectator: A Powerful Tool to Simplify Your Angular Tests
- Transloco: The Internationalization library Angular
- error-tailor — Seamless form errors for Angular applications
- Forms Manager: The Foundation for Proper Form Management in Angular
- Cashew: A flexible and straightforward library that caches HTTP requests
- Error Tailor — Seamless form errors for Angular applications
And many more!
Follow me on Medium or Twitter to read more about Angular, Akita and JS!