问题
Consider the following route config:
route
..addRoute(
name: 'custom',
defaultRoute: true,
path: '/:param1/:param2',
enter: view('view/template.html')
);
I am injecting the router into a controller and setting up router.onRouteStart.listen
, within which I am accessing parameters via router.activePath.last.parameters
, now, if param2
is not present in the user entered route, then i want to assign a default value to param2
(also replace the route). How do I go about it?
回答1:
After a bit more of exploration found this sample on angular.dart.tutorial: https://github.com/angular/angular.dart.tutorial/blob/master/Chapter_06/lib/routing/recipe_book_router.dart#L19-L24
Which has the following way of doing it (changes according to my sample code):
route
..addRoute(
name: 'default',
defaultRoute: true,
path: '/:param1',
enter: (RouteEnterEvent e) =>
router.go('custom', {
'param1': router.activePath.last.parameters['param1'],
'param2': 'defaultValue'},
//[Optional, if mounted in a nested route]
//startingFrom: router.root.findRoute('custom_head'),
replace: true))
..addRoute(
name: 'custom',
defaultRoute: true,
path: '/:param1/:param2',
enter: view('view/template.html')
);
If the user doesn't provide a value for param2 then the first route gets activated, which will assign a default value for param2 and force update of url by replacing earlier one.
来源:https://stackoverflow.com/questions/22871434/how-to-assign-default-values-for-routing-parameters-in-angular-dart