Challenge your understanding of Angular routing with questions on navigation, route guards, lazy loading, and parameter handling. This quiz is designed for developers looking to improve their skills in configuring and protecting routes, optimizing app load times, and working with dynamic URLs in Angular projects.
Which scenario best demonstrates the use of a route guard to prevent navigation to a '/dashboard' route if a user is not authenticated?
Explanation: A canActivate guard intercepts navigation and checks conditions, such as user authentication, before allowing access to a specific route like '/dashboard'. Simply importing a Guard class does not enforce any protection unless it is actually applied to the route. The canDeactivate guard is used for deactivation behavior, not activation. Setting route params does not offer any protection; it only passes data.
How should a feature module named 'AdminModule' be configured for lazy loading in Angular's route definitions?
Explanation: Lazy loading is achieved by using the loadChildren property in the route, typically combined with a dynamic import for 'AdminModule'. Importing the module directly in AppModule would eagerly load it, defeating the purpose. Applying canLoad guard alone does not implement lazy loading; it only guards it. Assigning a module as a component is a syntax error, as route components expect component classes, not modules.
When a user navigates to '/profile/42', which approach correctly retrieves the dynamic 'id' parameter in the ProfileComponent?
Explanation: ActivatedRoute provides access to route parameters, and snapshot.params['id'] gives the value of 'id' for the current route. Router.navigateByUrl is used for navigation, not parameter retrieval. The @Input decorator is intended for parent-to-child component communication, not route parameters. The routerLink directive is for navigation only; it doesn't expose parameters to components.
If a feature module for '/settings' is lazy-loaded, which statement best describes the difference between canActivate and canLoad guards in this context?
Explanation: canLoad stops the lazy-loaded module from being downloaded if the guard condition fails, making it useful for resource protection. canActivate runs after the module is loaded, checking route access. The second option is incorrect, as canLoad does not check URL params specifically. The third option is wrong; their behaviors differ. Both canLoad and canActivate can be used on feature modules, not restricted to root or child modules.
Given a route '/search', how can you navigate to it with a query parameter 'q=music' using Angular's Router service?
Explanation: router.navigate with the queryParams option is the standard way to programmatically pass query parameters like 'q' in Angular. router.open does not exist in Angular's API. router.linkTo and router.go are not valid Router service methods, and the syntax for params is incorrect for query parameters in the last option.