Build Angular Router navigation: first-match routes, canMatch, guards with UrlTree redirects and resolvers
Problem
Angular's router turns a URL into a chain of activated routes, and every step of a navigation can be asynchronous: canMatch while matching, canDeactivate, canActivateChild and canActivate guards, then resolvers. Interviewers ask about the order of these steps, what happens when a guard returns a UrlTree, and what happens to a slow navigation when the user clicks somewhere else. Build that navigation pipeline.
let router;
router = createRouter([
{ path: "login", component: Login },
{ path: "orders", component: Orders, canActivate: [() => auth.loggedIn || router.parseUrl("/login")] },
{ path: "**", component: NotFound },
]);
await router.navigate("/orders"); // true, but router.url === "/login"
router.events.map((e) => e.type); // NavigationStart, NavigationCancel, NavigationStart, NavigationEndRef. UR-1453 · © UIRound · uiround.com/questions/build-angular-router-navigation-first-match-routes-canmatch-guards-with-urltree-redirects-and-resolvers
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 8
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Split a navigation into phases and check after every
awaitwhether a newer navigation has started: recognise (match routes, runcanMatch, applyredirectTo), compare with the current route chain, run guards, run resolvers, then commit.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.