Default, Redirect and Wildcard Routes (DRAFT) 6.0
Milestone
Default route
The initial URL in the browser bar after the app launches is something like localhost:8080.
That doesn’t match any of the configured routes, which means that the app won’t display any component when it’s launched. The user must click one of the links to trigger a navigation and component display.
It would be nicer if the app had a default route
that displayed the list of heroes immediately.
One way to achieve this is to add useAsDefault: true
as an argument
to the Heroes
route definition:
lib/src/routes.dart (useAsDefault)
static final heroes = RouteDefinition(
routePath: RoutePaths.heroes,
component: hero_list_template.HeroListComponentNgFactory,
useAsDefault: true,
);
open_in_browser
Refresh the browser and try it. Notice that the heroes list is displayed
when the app launches, but that the URL path is /
.
Redirect route
As an alternative solution, remove the useAsDefault
argument that you just added,
and instead add a redirect route that will translate an initial relative path ('/'
)
to the desired default path (/#/heroes
).
lib/src/routes.dart (redirect)
static final all = <RouteDefinition>[
// ···
RouteDefinition.redirect(
path: '',
redirectTo: RoutePaths.heroes.toUrl(),
),
// ···
];
open_in_browser
Refresh the browser and try it. Now the browser address bar path is /#/heroes
as if you’d navigated there directly.
Wildcard route
While you’ve created routes to /#/crises
and /#/heroes
,
what if the router is given another path?
Add a wildcard route so that all other paths are handled
by a “Not Found” (404) component:
lib/src/routes.dart (wildcard)
static final all = <RouteDefinition>[
// ···
RouteDefinition(
path: '.+',
component: not_found_template.NotFoundComponentNgFactory,
),
];
The path regular expression '.+'
matches every non-empty path.
(Exclude the empty path so that it triggers the useAsDefault
route you defined earlier.)
The router will select the wildcard route if it can’t match a route earlier in the routes list.
App code
In this short iteration you’ve tried default, redirect and wildcard routes. Here are the files that were added or edited: