Oct 12, 2018

Angular - Router Guard

Angular router provides several types of guards. Guard is an angular injectable service which you register as a provider and use it when you configure a route. You also have an option to create it just like a function, but typically in production code, you will have a service. Following is the order in which guards are executed and if any guard returns false, all pending guards are canceled, and the requested navigation is canceled.
  • canDeactivate - The router first executes the canDeactivate guards for the current route to determine whether the user can leave that route.
  • canLoad - If a feature module is loaded asynchronously, the canLoad route guard is checked before the module is loaded; it won't even be downloaded unless the guard requirements are met. Unlike the canActivate, the canLoad method cannot access the ActivatedRouteSnapshot or RouterStateSnapshot because the module defining the route is not yet loaded.
  • canActivateChild - This is to guard activation to a child route to protect child route
  • canActivate - Guard to protect the route.
  • resolve - After all other route guards are checked, the resolvers are executed, so you resolve only when you have access to the route. This is typically used to fetches data before the component is activated. This way component doesn't have to show partial data or put special logic to work around that while data is being downloaded from the server.

The router extracts any route parameters from the URL and supplies them to the component through its ActivatedRoute service. It provides access to URL segments, route parameters, query parameters, route data and even access to the parent route. These are exposed as observables so you can subscribe which will notify of any parameter change. A controller onInit is only called once when a component is initialized, meaning route parameter change (navigating from app/1 to app/2 in cased of route like app/:id) will not call onInit, so to make sure you update your component based on id in the browser, you get hold of the ActivatedRoute and then subscribe to param change. On the other hand routeguard will be called every time, even when route parameter change and it will be passed with ActivatedRouteSnapshot, which has same properties as ActivatedRouty as plain values, while ActivatedRoute exposes them as observables.

No comments:

Post a Comment