Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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
Tweet

More Decks by Nishu Goel

Other Decks in Technology

Transcript

  1. The Angular Router
    Hello Trivandrum!
    TRIVANDRUM TECHCON20

    View Slide

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

    View Slide

  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

    View Slide

  4. Angular Router
    the official library for routing
    in the angular-based web
    applications. It comes
    packaged as
    @angular/router.

    View Slide

  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

    View Slide

  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.

    View Slide

  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

    View Slide

  8. navigate!
    route from template:
    Profile
    route from code:
    this._router.navigate(['errorpage']);
    @DcoustaWilson

    View Slide


  9. It is like a placeholder for
    the next view.



    Tip
    Only see the route
    change but not view?
    place it exactly where
    you want the next
    component view.

    View Slide

  10. Try this out here.

    View Slide

  11. View Slide

  12. View Slide

  13. Wildcard route?

    View Slide

  14. View Slide

  15. Router lifecycle
    let us understand the

    View Slide

  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

    View Slide

  17. View Slide

  18. Give this a try here.

    View Slide

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

    View Slide

  20. View Slide

  21. navigate! but, wait!

    View Slide

  22. Are we allowed to navigate? check for guards

    View Slide

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

    View Slide

  24. before proceeding to the next router event, let us look at other guards:
    the order of execution of guards

    View Slide

  25. canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
    ): Observable|Promise|boolean|UrlTree {
    return this.permissions.canActivate(this.currentUser, route.params.id);
    }
    Create a guard
    ng g guard
    canActivate guard function
    always runs before fetching the data, pointless to
    load data before ensuring if activation will take place.

    View Slide

  26. Without route resolvers

    View Slide

  27. resolvers
    prefetch component data during routing
    @DcoustaWilson

    View Slide

  28. With route resolvers

    View Slide

  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

    View Slide

  30. Lazy Loading
    asynchronously load
    the feature module for
    routing whenever
    required.

    View Slide

  31. View Slide

  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

    View Slide

  33. Lazy loading bundle
    difference

    View Slide

  34. View Slide

  35. View Slide

  36. Lazy load routes here.

    View Slide

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

    View Slide

  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

    View Slide

  39. View Slide

  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')

    View Slide

  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]));

    View Slide

  42. https://medium.com/angular-in-
    depth/the-angular-router-in-the-
    newer-versions-b50e2ced5d5

    View Slide

  43. Resources
    - Angular changelog
    - Angular documentation
    - Angular router series, Nate Lipinski
    - Book - Step by Step Angular Routing
    @DcoustaWilson

    View Slide

  44. Dive deeper into the router
    here:
    https://amzn.to/2t54EVI

    View Slide

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

    View Slide