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

Routing in Angular

Routing in Angular

Find Google Slides @ https://bit.ly/ng-routing

Hardik Pithva

December 29, 2017
Tweet

More Decks by Hardik Pithva

Other Decks in Technology

Transcript

  1. Overview • Enables navigation from one view to another •

    Browser : ◦ URL in the address bar ◦ Links on the page ◦ Back and forward buttons
  2. <> /login Login Page <> / Landing Page <> /register

    Register Page <> /movie/detail/:id Detail Page <> /movie Movie Page <> /movie/cast/:id Cast Page Child Routes Secure Route <> /movie/add Add Movie Page <> /admin Admin Page Secure Route
  3. • Routes • Router ◦ Module ◦ Outlet ◦ Link

    ◦ State ◦ Guard ◦ Parameters ◦ Animations • Child routes • Lazy routes
  4. <base href> • Specifies the base URL to use for

    all relative URLs • Only one <base> element in a document. • <base> as the first child in the <head> <base href="/"> src/index.html
  5. Router • Separate library package @angular/router • Presents specific component’s

    view for a given URL import {RouterModule, Routes} from '@angular/router; src/app/app.module.ts
  6. import { Routes, RouterModule } from "@angular/router"; const routes: Routes

    = [ { path: '', component: DashboardComponent }, { path: 'movies', component: MoviesComponent }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent }, { path: '**', redirectTo: '/', pathMatch: 'full' }, ] @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } app-routing.module.ts
  7. Router outlet • A directive, acts as placeholder • View

    of requested component is rendered after RouterOutlet once URL matches. <router-outlet></router-outlet> Place into the container file <router-outlet></router-outlet> <router-outlet name=”left”></router-outlet> <router-outlet (activate)=”onActivate($event)”></router-outlet> Multiple outlets
  8. <header> <ul> <li><a class="brand" routerLink="/">Movies</a></li> <li><a routerLink="/">Home</a></li> <li><a routerLink="/movies">Movies</a></li> </ul>

    </header> <div class="container"> <router-outlet></router-outlet> </div> <footer> ... </footer> app.component.html Placeholder
  9. Router links • RouterLink directives on <a> give the router

    control ◦ queryParams lets you pass data (in case default) • RouterLinkActive directive helps recognizing activated route src/app/app.component.ts <ul> <li><a routerLink="/dashboard" routerLinkActive="active">Dashboard</a></li> <li><a routerLink="/movies" routerLinkActive="active">Movies</a></li> </ul>
  10. Router state • A tree of ActivatedRoute objects • Traverse

    up and down the route tree • Activated route ◦ Route path, parameters and other information (fragment, outlet, etc) available • Router events ◦ Emits navigation events, range from start and ends to many points in between
  11. Child routes • Angular router allows us to create child

    routes • Nested underneath a certain route
  12. const movieRoute: Routes = [ { path: 'movies', component: MoviesComponent,

    children: [ { path: '', component: MovieListComponent }, { path: 'details/:id', component: MovieDetailsComponent } ] }, ...Other Routes ] @NgModule({ imports: [RouterModule.forChild(movieRoute)], exports: [RouterModule] }) export class MovieRoutingModule { } movie-routing.module.ts
  13. • Load feature areas only when requested • Improved performance

    for users • No increasing the size of the initial load bundle Lazily loaded Note : Modules, like AppModule, must be loaded from the start. But others can and should be lazily loaded. { path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule', }, ...Other Routes app-routing.module.ts
  14. const routes: Routes = [ { path: '', component: DashboardComponent

    }, { path: 'login', loadChildren: 'app/login/login.module#LoginModule' }, { path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule' }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent }, { path: '**', redirectTo: '/', pathMatch: 'full' }, ] @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } app-routing.module.ts Lazy Modules (Login & Admin)
  15. const adminRoutes: Routes = [ { path: '', component: AdminComponent,

    children: [ { path: '', component: AdminComponent }, { path: 'movie/add', component: MovieComponent } ] } ]; @NgModule({ imports: [RouterModule.forChild(adminRoutes)], exports: [RouterModule], }) export class AdminRoutingModule { } import { AdminRoutingModule } from "./admin-routing.module"; import { AdminComponent } from "./admin.component"; @NgModule({ imports: [ AdminRoutingModule, .... ], declarations: [ AdminComponent ... ] }) export class AdminModule { } admin/admin-routing.module.ts admin/admin.module.ts
  16. Analyze with Source Map npm install -g source-map-explorer Install globally

    ng build Build Angular App source-map-explorer dist/main.bundle.js dist/main.bundle.js.map Analyze app bundle
  17. • Add guards to the configuration ◦ Returns true/false or

    Observable<boolean>/Promise<boolean> ◦ Can be synchronous/asynchronous operation • Implement multiple guards interfaces ◦ CanActivate ◦ CanActivateChild ◦ CanDeactivate ◦ Resolve ◦ CanLoad Securing routes
  18. CanActivate / CanActivateChild No anonymous access to routes, helps to

    secure it CanDeactivate Control activated route, notify user before navigating
  19. import { AuthGuard } from "../auth/auth-guard.service"; const adminRoutes: Routes =

    [ { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [ { path: '', canActivateChild: [AuthGuard], canDeactivate: [DeactivateGuard], children: [ { path: 'movie/add', component: MovieComponent } ] } ] } ]; @NgModule({...}) export class AdminRoutingModule { } admin/admin-routing.module.ts Secure parent route Secure child route Control route e.g. Prompt user before navigating while filling form for unsaved changes canActivate canActivateChild canDeactivate
  20. import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, CanActivateChild, Router} from '@angular/router'; @Injectable()

    export class AuthGuard implements CanActivate, CanActivateChild { constructor(private router: Router, private userService: UserService) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { let status = this.userService.validate(); if (!status) this.router.navigate(['/login'], { queryParams: { returnUrl: atob(state.url) } }); return status; } canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return this.canActivate(route, state); } } guards/auth-guard.service.ts Pass parameters to resolve requested URL canActivate canActivateChild
  21. import { Injectable } from '@angular/core'; import { CanDeactivate }

    from "@angular/router"; import { MovieComponent } from "../admin/movie/movie.component"; @Injectable() export class DeactivateGuard implements CanDeactivate<MovieComponent> { canDeactivate(component: MovieComponent) { return component.canDeactivate ? component.canDeactivate() : true; } } guards/deactivate-guard.service.ts canDeactivate
  22. import { ActivatedRouteSnapshot, Resolve } from "@angular/router"; import { Observable

    } from "rxjs/Rx"; import { Movie } from "./movie"; import { MovieService } from "./movie.service"; @Injectable() export class MovieResolver implements Resolve<Movie[]> { constructor(private movieService: MovieService) { } resolve(route: ActivatedRouteSnapshot): Observable<Movie[]> { return this.movieService.getMovies(); } } movies/movie-resolver.service.ts resolve
  23. import { MovieResolver } from "./movie-resolver.service"; const movieRoute: Routes =

    [ { path: 'movies', component: MoviesComponent, children: [ { path: '', component: MovieListComponent, resolve: { movies:MovieResolver } }, { path: 'details/:id', component: MovieDetailsComponent } ] } ] movies/movie-routing.module.ts Movie resolver resolve
  24. const routes: Routes = [ { path: '', component: DashboardComponent

    }, { path: 'login', loadChildren: 'app/login/login.module#LoginModule' }, { path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule', canLoad: [AuthGuard] }, ...Other Routes ] @NgModule({...}) export class AppRoutingModule { } app-routing.module.ts canLoad
  25. Get the content and stay tuned • Slides : goo.gl/WKXUHF

    • Repo. : github.com/online-edu/movie-app • Demo : movie-app-29a50.firebaseapp.com • Tutorials : youtube.com/onlineedu