[Angular] Routing Helper - a Typesafe Routing Attempt
Georg Höller -
It always bothered me that you have to define the routing paths as strings. If a route changes, you have to change all references manually. There must be a better way!
Routing Constants
The constants are for your specific app - here you can define a class which represents your entire routing. Place it in an utils library, core folder or somewhere where your constants live.
Routing Helper
This should be the generic API - place it in a shared folder.
Let's go through it step by step:
In the constructor we set the routingMap and initialize it. The method addRoutingProperties adds two helper properties to each path.
_pathProp: path for routing definition
_navRoute: contains the navigation string array
As you already recognized the API code isn't typesafe. (if you find a way, let me know!). So I added two methods to provide typesafe-like access to the helper properties.
getPath Takes a lambda expression as parameter and returns the property name as string. Example usage:
To handle param routes (e.g. :id) I implemented the constant ID_ROUTE_END. It defines that any route which ends with 'Id' should be handled like an param route. So you can do something like this:
.getPath((p) => p.routing.parent.parentId) - will result in 'parent/:parentId'
.getNavRoute((p => p.routing.parent.parentId.details.childId), '1', '2') - will result in ['/', 'routing', 'parent', '1', 'details', '2']
☝️
This code is by far not perfect - feel free to extend and change it! Suggestions for improvement are welcome in chat or by mail!
Routing Helper Source:
Implementation Example:
If you have further questions about this topic or need help with a problem in general, please write a comment or simply contact me at yesreply@georghoeller.dev :)