2
votes

I know that Aurelia route modules can be specified dynamically using navigationStrategy but that does not work for my purposes because the toggle value resides in the RouterConfiguration that only runs once. I need a way to route to different views where the toggle value can change multiple times during one session. Additionally, not all routes have multiple views.

What is the best practice for routing to different views on the same route based on a dynamic value?

I've come up with a few different strategies but I'm not sure which one is the most acceptable way to do this.

  • Using viewPorts where the route will have a static moduleId to a view that injects the name into an instance of <router-view name="view1_index"></router-view> using a global string, e.g. 'view1' may be passed down as 'view2', etc.

  • Using 2 or more instances of <compose> where the route will again have a static moduleId to a view that will use a global variable to toggle an if.bind in the <compose> instances

  • Using canActivate in the route module and redirecting to the secondary viewport if conditions are met

  • Using a pipeline step in the router config to evaluate whether it should direct to a different module (if this is possible)

Which of these strategies, if any, is most accepted? If all of these are odd ways of routing to different views per route, what should be done?

1

1 Answers

1
votes

What is the best practice for routing to different views on the same route based on a dynamic value?

Compose is your best bet. It is common to pass a parameter to the route, capture the parameter in the activate(params) callback, set a variable on your view model using the params, and then use that variable to set the view-model attribute of <compose>.

Using a pipeline step in the router config to evaluate whether it should direct to a different module (if this is possible)

This is very possible. A common use case is authentication, where you use the AuthorizeStep to check whether a user is authorized and redirect him away if he is not. See http://foreverframe.net/exploring-aurelia-pipelines/. This can be activated in the PreactivateStep as well.

Using viewPorts where the route will have a static moduleId to a view that injects the name into an instance of using a global string, e.g. 'view1' may be passed down as 'view2', etc.

I recommend against using viewports for anything other than associating routes to views on a certain section of the screen.

Edit:

A third option you might be interested in is returning a Redirect from your canActivate() function.

import { Redirect } from 'aurelia-router';

canActivate(params) {
  let thing = this.thing = await this.service.getById(params.id);
  if (!thing) {
    return new Redirect('somewhere');
  }
  return true;
}