$30 off During Our Annual Pro Sale. View Details »

The Angular Router - TrivandrumTechCon20

Nishu Goel
January 25, 2020

The Angular Router - TrivandrumTechCon20

This presentation talks about the Angular router covering the basic routing technique, Angular router events, guards, route resolvers, lazy loading of routes, and the latest changes in the Angular router (Angular v7, v8, v9)

Nishu Goel

January 25, 2020

More Decks by Nishu Goel

Other Decks in Technology


  1. The Angular Router Hello Trivandrum! TRIVANDRUM TECHCON20

  2. Nishu Goel @DcoustaWilson Developer, UI Garage, IBM Blog: https://nishugoel.wordpress.com/ GitHub:

  3. 1. Agenda ➔ What is Angular Router? ➔ Router Lifecycle

    Events, guards, resolvers ➔ Lazy Loading of routes dynamically load modules ➔ Updates in Latest versions Angular version 7, 8, 9
  4. Angular Router the official library for routing in the angular-based

    web applications. It comes packaged as @angular/router.
  5. - Navigates to the configured routes for the components which

    are routable. - import the RouterModule - configure the router states - navigate from one view to another
  6. Import the RouterModule import { Routes, RouterModule } from '@angular/router';

    @NgModule({ imports: [RouterModule.forRoot(routes)] }) Tip With a separate routing module, AppRoutingModule, export the RouterModule in the exports array.
  7. const routes: Routes = [ { path: 'connect', component: ConnectComponent

    }, { path: 'profile', component: ProfileComponent, }, { path: ‘**’, component: WildCardComponent } Tip Do not place the wildcard route before any other, as the route states are checked in the order defined in the configuration. configure the router states
  8. navigate! route from template: <div [routerLink]="'/profile'">Profile</div> route from code: this._router.navigate(['errorpage']);

  9. <router-outlet> It is like a placeholder for the next view.

    <section class="body-section"> <router-outlet></router-outlet> </section> Tip Only see the route change but not view? place it exactly where you want the next component view.
  10. Try this out here.

  11. None
  12. None
  13. Wildcard route?

  14. None
  15. Router lifecycle let us understand the

  16. observing the life cycle constructor(private router: Router) { this.router.events.subscribe( (event:

    RouterEvent) => console.log(event)) } Tip RouterModule.forRoot(ROUTES, { enableTracing: true }); For debugging purpose
  17. None
  18. Give this a try here.

  19. events: - NavigationStart - RoutesRecognized (signalled when URL matched, or

  20. None
  21. navigate! but, wait!

  22. Are we allowed to navigate? check for guards

  23. If the guard fails, the router emits a NavigationCancel event.

  24. before proceeding to the next router event, let us look

    at other guards: the order of execution of guards
  25. canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { return this.permissions.canActivate(this.currentUser,

    route.params.id); } Create a guard ng g guard <guard-name> canActivate guard function always runs before fetching the data, pointless to load data before ensuring if activation will take place.
  26. Without route resolvers

  27. resolvers prefetch component data during routing @DcoustaWilson

  28. With route resolvers

  29. Finally, activation! private updateTargetUrlAndHref(): void { this.href = this.locationStrategy.prepareExternalUrl(this.router. serializeUrl(this.urlTree));

    } events: ActivationStart, ActivationEnd, ChildActivationStart, ChildActivationEnd NavigationEnd - update the URL in the browser
  30. Lazy Loading asynchronously load the feature module for routing whenever

  31. None
  32. {path: ‘user’, loadChildren: () => import(‘./users/user.module’).then(m => m.UserModule)}; canLoad guard

    load a particular module only if it can be loaded. This means that check the criteria before loading it Read about preloading strategies here: https://angular.io/guide/ro uter#how-preloading- works
  33. Lazy loading bundle difference

  34. None
  35. None
  36. Lazy load routes here.

  37. Updates in the router (v7, v8, v9)

  38. v7 - add pathParamsChange mode for runGuardsAndResolvers runGuardsAndResolvers: ‘ paramsChange’

    - Return UrlTree from guard const tree: UrlTree = this.router.parseUrl(url); - Guard priority using prioritizedGuardValue Observable<boolean|UrlTree>
  39. None
  40. v8 - Dynamic import of lazy loaded routes Earlier: {path:

    ‘user’, loadChildren: ‘./users/user.module#UserModule’} Now: {path: ‘user’, loadChildren: () => import(‘./users/user.module’).then(m => m.UserModule)}; - add hash-based navigation option to setUpLocationSync setUpLocationSync(ngUpgrade: UpgradeModule, urlType: "path" | "hash" = 'path')
  41. v9 - make routerLinkActive work with query params which contain

    arrays Object.keys(containee).every(key => containee[key] === container[key]); //changed to Object.keys(containee).every(key => equalArraysOrString(container[key], containee[key]));
  42. https://medium.com/angular-in- depth/the-angular-router-in-the- newer-versions-b50e2ced5d5

  43. Resources - Angular changelog - Angular documentation - Angular router

    series, Nate Lipinski - Book - Step by Step Angular Routing @DcoustaWilson
  44. Dive deeper into the router here: https://amzn.to/2t54EVI

  45. Thank you so much! github.com/NishuGoel @DcoustaWilson nishugoel.wordpress.com