Tuesday, September 4, 2018

Angular 6 - Routing How to do it


While developing Angular apps, I thought of compiling a list of things we need to know on each of the areas. Here I cover routing.

Basics
  • A routed Angular application has one singleton instance of the Router service
  • The router uses a first-match wins strategy
    • The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first
    • Use path: '**' to match invalid routes (any other route that is not defined) for 404 redirections
  • Use enableTracing: true for debugging purposes by passing as 2nd parameter to forRoot
  • The router uses browsers history.pushState for navigation
Router Link
  • Use RouterLinkActive directive helps identify active links. The router adds active css class to the a tag
  • After the end of each successful navigation life cycle, the router builds a tree of ActivatedRoute objects that make up the current state of the router. You can access the current RouterState from anywhere in the application using the Router service and the routerState property.

  • The router adds the <router-outlet> element to the DOM and subsequently inserts the navigated view element immediately after the <router-outlet>.
  • You can add redirectRoute for redirections (defined in router module)
  • Only call RouterModule.forRoot in the root AppRoutingModule (or the AppModule if that's where you register top level application routes). In any other module, you must call the RouterModule.forChild method to register additional routes. (article)
  • Always put app routing as last in main module
Authentication
  • Use CanActivate guard to manage navigation business rules
  • You can create component-less routes to manage authentication easily
  • You can create a service which extends CanActivate which coul contain the security logic
    • Use canActivate attribute with that service
  • You can use CanActivateChild guard to protect child routes. It runs before any child route is activated

2 comments:

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook