Slide 1

Slide 1 text

Routing in Angular Hardik Pithva @hardikpthv

Slide 2

Slide 2 text

Overview ● Enables navigation from one view to another ● Browser : ○ URL in the address bar ○ Links on the page ○ Back and forward buttons

Slide 3

Slide 3 text

<> /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

Slide 4

Slide 4 text

flic.kr/p/QbmMf7 Routing Configuration

Slide 5

Slide 5 text

● Routes ● Router ○ Module ○ Outlet ○ Link ○ State ○ Guard ○ Parameters ○ Animations ● Child routes ● Lazy routes

Slide 6

Slide 6 text

● Specifies the base URL to use for all relative URLs ● Only one element in a document. ● as the first child in the src/index.html

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

Router outlet ● A directive, acts as placeholder ● View of requested component is rendered after RouterOutlet once URL matches. Place into the container file Multiple outlets

Slide 10

Slide 10 text

... app.component.html Placeholder

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

Child routes ● Angular router allows us to create child routes ● Nested underneath a certain route

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

goo.gl/images/CJcvGg A -synchronous routing

Slide 16

Slide 16 text

● 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

Slide 17

Slide 17 text

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)

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

http://localhost:4200/admin/movie/add Eagerly Loaded

Slide 20

Slide 20 text

http://localhost:4200/admin/movie/add Lazily Loaded New file loaded on demand

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

Lazily Loaded Eagerly Loaded

Slide 23

Slide 23 text

Route Guards in

Slide 24

Slide 24 text

● Add guards to the configuration ○ Returns true/false or Observable/Promise ○ Can be synchronous/asynchronous operation ● Implement multiple guards interfaces ○ CanActivate ○ CanActivateChild ○ CanDeactivate ○ Resolve ○ CanLoad Securing routes

Slide 25

Slide 25 text

CanActivate / CanActivateChild No anonymous access to routes, helps to secure it CanDeactivate Control activated route, notify user before navigating

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

import { Injectable } from '@angular/core'; import { CanDeactivate } from "@angular/router"; import { MovieComponent } from "../admin/movie/movie.component"; @Injectable() export class DeactivateGuard implements CanDeactivate { canDeactivate(component: MovieComponent) { return component.canDeactivate ? component.canDeactivate() : true; } } guards/deactivate-guard.service.ts canDeactivate

Slide 29

Slide 29 text

Resolve Prefetch data before route gets activated

Slide 30

Slide 30 text

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 { constructor(private movieService: MovieService) { } resolve(route: ActivatedRouteSnapshot): Observable { return this.movieService.getMovies(); } } movies/movie-resolver.service.ts resolve

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

CanLoad Prevents the app to load entire module if unauthorized; unlike CanActivate

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

View @ movie-app-29a50.firebaseapp.com

Slide 36

Slide 36 text

Thank You Hardik Pithva @hardikpthv

Slide 37

Slide 37 text

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