Routing - choosing from multiple url fragments


#1

For new/edit routes I mostly want the view-model and view to be the same, so I would like to use url fragments in my route definition:

{
    route: [":rId/edit", "new"], name: "edit",
    moduleId: PLATFORM.moduleName("edit"), title: "Foo"
},
{  route: ":rId", name: "view", ... }

but I find there’s no way of choosing which url fragment gets used when routing from either a router.navigateToRoute() or route-href. e.g. I would want to do either to navigate:

  • this.router.navigateToRoute("edit", { rId: 123 }); or
  • this.router.navigateToRoute("edit");

this works, in that both will route to the correct page, but the former creates the url:

  • /new?rId=123 instead of
  • /123/edit

To get around it, I specify two route definitions that use the same module:

{
    route: ":rId/edit", name: "edit",
    moduleId: PLATFORM.moduleName("edit"), title: "Edit Foo"
},
{
    route: "new", name: "new",
    moduleId: PLATFORM.moduleName("edit"), title: "New Foo"
}

and now I can choose to navigate to “new” or “edit”.

Would it be possible to choose the url fragment (or allow the recognizer (I think it’s called) to choose the correct fragment based on how utilized the parameters are)?

My workaround works, but a bit less repetition would be ideal.

thanks!


#2

I’d say your solution is the proper way to go. There really isn’t any duplication except for the moduleId value. You could define a constant for that:

const editModule = PLATFORM.moduleName("edit");


#3

I’m still duplicating the whole route definition. I know I used different titles and names, but the name is just to identify them and the title can be the same. Perhaps I should have rephrased my last line to “some way to influence the url fragment chosen when matching a route”!

Thanks :wink:


#4

The best practice would be to use a more general route configuration:

{ route: 'edit/:id?', name: 'edit', ... }

This results in:

router.navigateToRoute('edit'); // 'edit'
router.navigateToRoute('edit', { id: 123 }); // 'edit/123'

There currently isn’t any logic to support intelligently switching between different route definitions based on passed parameters. This is a bit of an edge case since the above route definition solves the problem.

If you wanted the “new” route as well, do what you’re doing here. It’s a perfectly legitimate strategy. As Jeff said, it doesn’t seem repetitive to me either.