Richard Johnson
Richard Johnson

Reputation: 561

Dart Angular 5 router child redirectTo needs parent parameter

We need to redirect a child route to another child route and maintain a parent route parameter. For example redirect the route /u/2/object/123 to /u/2/list. Routing (for this simplified example) is handled by parent and child RouteDefinition levels. The parent definition would be

RouteDefinition(path: 'u/:index', component: ...

The child would be

RouteDefinition(path: 'list', component: ...
RouteDefinition(path: 'object/:id', component: ...
RouteDefinition.redirect(path: '.*', redirectTo: 'u/:index/list')

Running this returns error FormatException: :index so parameters in redirectTo URLs don't seem to be currently supported. Relative routes are also not supported.

We are using Dart Angular 5 so RouteDefinitions must be defined and given to the router-outlet before any of the router events fire. This seems to preclude use of procedural redirection at the child level. Are there any other solutions other than overriding the top level router?

Upvotes: 1

Views: 358

Answers (1)

Richard Johnson
Richard Johnson

Reputation: 561

I created a component that only redirects in its CanActivate handler. The child RouteDefinition uses a component instead of a .redirect:

new RouteDefinition(path: '.*', component: RedirectTo.RedirectToNgFactory),

I have RoutePath definitions:

final user = new RoutePath(path: 'u/:index');
final list = new RoutePath(parent: user, path: 'list');

The component's CanActivate handler is given the route path and parameters. It always does a router.navigate:

@Component(
  selector: 'redirect-to',
  template: '',
)
class RedirectTo implements CanActivate {

  final Router router;

  RedirectTo(this.router);

  Future<bool> canActivate(RouterState current, RouterState next) async {
    router.navigate( list.toUrl(parameters: next.parameters) );
    return false;
  }
}

Upvotes: 0

Related Questions