{ "id": "guide/router-tutorial-toh", "title": "Router tutorial: tour of heroes", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n \n

Router tutorial: tour of heroeslink

\n

This tutorial provides an extensive overview of the Angular router.\nIn this tutorial, you will build upon a basic router configuration to explore features such as child routes, route parameters, lazy load NgModules, guard routes, and preloading data to improve the user experience.

\n

For a working example of the final version of the app, see the .

\n\n

Objectiveslink

\n

This guide describes development of a multi-page routed sample application.\nAlong the way, it highlights key features of the router such as:

\n\n

This guide proceeds as a sequence of milestones as if you were building the app step-by-step, but assumes you are familiar with basic Angular concepts.\nFor a general introduction to angular, see the Getting Started. For a more in-depth overview, see the Tour of Heroes tutorial.

\n

Prerequisiteslink

\n

To complete this tutorial, you should have a basic understanding of the following concepts:

\n\n

You might find the Tour of Heroes tutorial helpful, but it is not required.

\n

The sample application in actionlink

\n

The sample application for this tutorial helps the Hero Employment Agency find crises for heroes to solve.

\n

The application has three main feature areas:

\n
    \n
  1. A Crisis Center for maintaining the list of crises for assignment to heroes.
  2. \n
  3. A Heroes area for maintaining the list of heroes employed by the agency.
  4. \n
  5. An Admin area to manage the list of crises and heroes.
  6. \n
\n

Try it by clicking on this live example link.

\n

The app renders with a row of navigation buttons and the Heroes view with its list of heroes.

\n
\n \"Hero\n
\n

Select one hero and the app takes you to a hero editing screen.

\n
\n \"Crisis\n
\n

Alter the name.\nClick the \"Back\" button and the app returns to the heroes list which displays the changed hero name.\nNotice that the name change took effect immediately.

\n

Had you clicked the browser's back button instead of the app's \"Back\" button, the app would have returned you to the heroes list as well.\nAngular app navigation updates the browser history as normal web navigation does.

\n

Now click the Crisis Center link for a list of ongoing crises.

\n
\n \"Crisis\n
\n

Select a crisis and the application takes you to a crisis editing screen.\nThe Crisis Detail appears in a child component on the same page, beneath the list.

\n

Alter the name of a crisis.\nNotice that the corresponding name in the crisis list does not change.

\n
\n \"Crisis\n
\n

Unlike Hero Detail, which updates as you type, Crisis Detail changes are temporary until you either save or discard them by pressing the \"Save\" or \"Cancel\" buttons.\nBoth buttons navigate back to the Crisis Center and its list of crises.

\n

Click the browser back button or the \"Heroes\" link to activate a dialog.

\n
\n \"Confirm\n
\n

You can say \"OK\" and lose your changes or click \"Cancel\" and continue editing.

\n

Behind this behavior is the router's CanDeactivate guard.\nThe guard gives you a chance to clean-up or ask the user's permission before navigating away from the current view.

\n

The Admin and Login buttons illustrate other router capabilities covered later in the guide.

\n\n

Milestone 1: Getting startedlink

\n

Begin with a basic version of the app that navigates between two empty views.

\n
\n \"App\n
\n\n

Generate a sample application with the Angular CLI.

\n\n ng new angular-router-sample\n\n

Define Routeslink

\n

A router must be configured with a list of route definitions.

\n

Each definition translates to a Route object which has two things: a path, the URL path segment for this route; and a component, the component associated with this route.

\n

The router draws upon its registry of definitions when the browser URL changes or when application code tells the router to navigate along a route path.

\n

The first route does the following:

\n\n

The first configuration defines an array of two routes with minimal paths leading to the CrisisListComponent and HeroListComponent.

\n

Generate the CrisisList and HeroList components so that the router has something to render.

\n\n ng generate component crisis-list\n\n\n ng generate component hero-list\n\n

Replace the contents of each component with the sample HTML below.

\n\n\n \n<h2>CRISIS CENTER</h2>\n<p>Get your crisis here</p>\n\n\n\n\n \n<h2>HEROES</h2>\n<p>Get your heroes here</p>\n\n\n\n\n\n

Register Router and Routeslink

\n

In order to use the Router, you must first register the RouterModule from the @angular/router package.\nDefine an array of routes, appRoutes, and pass them to the RouterModule.forRoot() method.\nThe RouterModule.forRoot() method returns a module that contains the configured Router service provider, plus other providers that the routing library requires.\nOnce the application is bootstrapped, the Router performs the initial navigation based on the current browser URL.

\n
\n

Note: The RouterModule.forRoot() method is a pattern used to register application-wide providers. Read more about application-wide providers in the Singleton services guide.

\n
\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { AppComponent } from './app.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { HeroListComponent } from './hero-list/hero-list.component';\n\nconst appRoutes: Routes = [\n { path: 'crisis-center', component: CrisisListComponent },\n { path: 'heroes', component: HeroListComponent },\n];\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule,\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n )\n ],\n declarations: [\n AppComponent,\n HeroListComponent,\n CrisisListComponent,\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n
\n

Adding the configured RouterModule to the AppModule is sufficient for minimal route configurations.\nHowever, as the application grows, refactor the routing configuration into a separate file and create a Routing Module.\nA routing module is a special type of Service Module dedicated to routing.

\n
\n

Registering the RouterModule.forRoot() in the AppModule imports array makes the Router service available everywhere in the application.

\n\n

Add the Router Outletlink

\n

The root AppComponent is the application shell. It has a title, a navigation bar with two links, and a router outlet where the router renders components.

\n
\n \"Shell\"\n
\n

The router outlet serves as a placeholder where the routed components are rendered.

\n\n

The corresponding component template looks like this:

\n\n<h1>Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/heroes\" routerLinkActive=\"active\">Heroes</a>\n</nav>\n<router-outlet></router-outlet>\n\n\n\n

Define a Wildcard routelink

\n

You've created two routes in the app so far, one to /crisis-center and the other to /heroes.\nAny other URL causes the router to throw an error and crash the app.

\n

Add a wildcard route to intercept invalid URLs and handle them gracefully.\nA wildcard route has a path consisting of two asterisks.\nIt matches every URL.\nThus, the router selects this wildcard route if it can't match a route earlier in the configuration.\nA wildcard route can navigate to a custom \"404 Not Found\" component or redirect to an existing route.

\n
\n

The router selects the route with a first match wins strategy.\nBecause a wildcard route is the least specific route, place it last in the route configuration.

\n
\n

To test this feature, add a button with a RouterLink to the HeroListComponent template and set the link to a non-existant route called \"/sidekicks\".

\n\n<h2>HEROES</h2>\n<p>Get your heroes here</p>\n\n<button routerLink=\"/sidekicks\">Go to sidekicks</button>\n\n\n\n

The application fails if the user clicks that button because you haven't defined a \"/sidekicks\" route yet.

\n

Instead of adding the \"/sidekicks\" route, define a wildcard route and have it navigate to a PageNotFoundComponent.

\n\n{ path: '**', component: PageNotFoundComponent }\n\n\n

Create the PageNotFoundComponent to display when users visit invalid URLs.

\n\n ng generate component page-not-found\n\n\n<h2>Page not found</h2>\n\n\n

Now when the user visits /sidekicks, or any other invalid URL, the browser displays \"Page not found\".\nThe browser address bar continues to point to the invalid URL.

\n\n

Set up redirectslink

\n

When the application launches, the initial URL in the browser bar is by default:

\n\n localhost:4200\n\n

That doesn't match any of the hard-coded routes which means the router falls through to the wildcard route and displays the PageNotFoundComponent.

\n

The application needs a default route to a valid page.\nThe default page for this app is the list of heroes.\nThe app should navigate there as if the user clicked the \"Heroes\" link or pasted localhost:4200/heroes into the address bar.

\n

Add a redirect route that translates the initial relative URL ('') to the desired default path (/heroes).

\n

Add the default route somewhere above the wildcard route.\nIt's just above the wildcard route in the following excerpt showing the complete appRoutes for this milestone.

\n\nconst appRoutes: Routes = [\n { path: 'crisis-center', component: CrisisListComponent },\n { path: 'heroes', component: HeroListComponent },\n { path: '', redirectTo: '/heroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n\n

The browser address bar shows .../heroes as if you'd navigated there directly.

\n

A redirect route requires a pathMatch property to tell the router how to match a URL to the path of a route.\nIn this app, the router should select the route to the HeroListComponent only when the entire URL matches '', so set the pathMatch value to 'full'.

\n\n
\n
Spotlight on pathMatch
\n

Technically, pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match ''.\nIn this example, the redirect is in a top level route so the remaining URL and the entire URL are the same thing.

\n

The other possible pathMatch value is 'prefix' which tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.\nThis doesn't apply to this sample app because if the pathMatch value were 'prefix', every URL would match ''.

\n

Try setting it to 'prefix' and clicking the Go to sidekicks button.\nSince that's a bad URL, you should see the \"Page not found\" page.\nInstead, you're still on the \"Heroes\" page.\nEnter a bad URL in the browser address bar.\nYou're instantly re-routed to /heroes.\nEvery URL, good or bad, that falls through to this route definition is a match.

\n

The default route should redirect to the HeroListComponent only when the entire url is ''.\nRemember to restore the redirect to pathMatch = 'full'.

\n

Learn more in Victor Savkin's\npost on redirects.

\n
\n

Milestone 1 wrap uplink

\n

Your sample app can switch between two views when the user clicks a link.

\n

Milestone 1 has covered how to do the following:

\n\n

The starter app's structure looks like this:

\n
\n
\n angular-router-sample\n
\n
\n
\n src\n
\n
\n
\n app\n
\n
\n
\n crisis-list\n
\n
\n
\n

crisis-list.component.css

\n
\n
\n

crisis-list.component.html

\n
\n
\n

crisis-list.component.ts

\n
\n
\n
\n hero-list\n
\n
\n
\n

hero-list.component.css

\n
\n
\n

hero-list.component.html

\n
\n
\n

hero-list.component.ts

\n
\n
\n
\n page-not-found\n
\n
\n
\n

page-not-found.component.css

\n
\n
\n

page-not-found.component.html

\n
\n
\n

page-not-found.component.ts

\n
\n
\n
\n app.component.css\n
\n
\n app.component.html\n
\n
\n app.component.ts\n
\n
\n app.module.ts\n
\n
\n
\n main.ts\n
\n
\n index.html\n
\n
\n styles.css\n
\n
\n tsconfig.json\n
\n
\n
\n node_modules ...\n
\n
\n package.json\n
\n
\n
\n

Here are the files in this milestone.

\n\n\n \n<h1>Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/heroes\" routerLinkActive=\"active\">Heroes</a>\n</nav>\n<router-outlet></router-outlet>\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { AppComponent } from './app.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nconst appRoutes: Routes = [\n { path: 'crisis-center', component: CrisisListComponent },\n { path: 'heroes', component: HeroListComponent },\n\n { path: '', redirectTo: '/heroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule,\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n )\n ],\n declarations: [\n AppComponent,\n HeroListComponent,\n CrisisListComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n\n \n<h2>HEROES</h2>\n<p>Get your heroes here</p>\n\n<button routerLink=\"/sidekicks\">Go to sidekicks</button>\n\n\n\n\n \n<h2>CRISIS CENTER</h2>\n<p>Get your crisis here</p>\n\n\n\n\n \n<h2>Page not found</h2>\n\n\n\n \n<html lang=\"en\">\n <head>\n <!-- Set the base href -->\n <base href=\"/\">\n <title>Angular Router</title>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n </head>\n\n <body>\n <app-root></app-root>\n </body>\n\n</html>\n\n\n\n\n\n

Milestone 2: Routing modulelink

\n

This milestone shows you how to configure a special-purpose module called a Routing Module, which holds your app's routing configuration.

\n

The Routing Module has several characteristics:

\n\n\n

Integrate routing with your applink

\n

The sample routing application does not include routing by default.\nWhen you use the Angular CLI to create a project that does use routing, set the --routing option for the project or app, and for each NgModule.\nWhen you create or initialize a new project (using the CLI ng new command) or a new app (using the ng generate app command), specify the --routing option.\nThis tells the CLI to include the @angular/router npm package and create a file named app-routing.module.ts.\nYou can then use routing in any NgModule that you add to the project or app.

\n

For example, the following command generates an NgModule that can use routing.

\n\nng generate module my-module --routing\n\n

This creates a separate file named my-module-routing.module.ts to store the NgModule's routes.\nThe file includes an empty Routes object that you can fill with routes to different components and NgModules.

\n\n

Refactor the routing configuration into a routing modulelink

\n

Create an AppRouting module in the /app folder to contain the routing configuration.

\n\n ng generate module app-routing --module app --flat\n\n

Import the CrisisListComponent, HeroListComponent, and PageNotFoundComponent symbols\njust like you did in the app.module.ts.\nThen move the Router imports and routing configuration, including RouterModule.forRoot(), into this routing module.

\n

Re-export the Angular RouterModule by adding it to the module exports array.\nBy re-exporting the RouterModule here, the components declared in AppModule have access to router directives such as RouterLink and RouterOutlet.

\n

After these steps, the file should look like this.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nconst appRoutes: Routes = [\n { path: 'crisis-center', component: CrisisListComponent },\n { path: 'heroes', component: HeroListComponent },\n { path: '', redirectTo: '/heroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n )\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AppRoutingModule {}\n\n\n\n

Next, update the app.module.ts file by removing RouterModule.forRoot in the imports array.

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\n\nimport { AppComponent } from './app.component';\nimport { AppRoutingModule } from './app-routing.module';\n\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule,\n AppRoutingModule\n ],\n declarations: [\n AppComponent,\n HeroListComponent,\n CrisisListComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n
\n

Later, this guide shows you how to create multiple routing modules and import those routing modules in the correct order.

\n
\n

The application continues to work just the same, and you can use AppRoutingModule as the central place to maintain future routing configuration.

\n\n

Benefits of a routing modulelink

\n

The routing module, often called the AppRoutingModule, replaces the routing configuration in the root or feature module.

\n

The routing module is helpful as your app grows and when the configuration includes specialized guard and resolver services.

\n

Some developers skip the routing module when the configuration is minimal and merge the routing configuration directly into the companion module (for example, AppModule).

\n

Most apps should implement a routing module for consistency.\nIt keeps the code clean when configuration becomes complex.\nIt makes testing the feature module easier.\nIts existence calls attention to the fact that a module is routed.\nIt is where developers expect to find and expand routing configuration.

\n\n

Milestone 3: Heroes featurelink

\n

This milestone covers the following:

\n\n

This sample app recreates the heroes feature in the \"Services\" section of the Tour of Heroes tutorial, and reuses much of the code from the .

\n\n\n

A typical application has multiple feature areas, each dedicated to a particular business purpose with its own folder.

\n

This section shows you how refactor the app into different feature modules, import them into the main module and navigate among them.

\n\n

Add heroes functionalitylink

\n

Follow these steps:

\n\n\n ng generate module heroes/heroes --module app --flat --routing\n\n\n
\n

Selectors are not required for routed components because components are dynamically inserted when the page is rendered. However, they are useful for identifying and targeting them in your HTML element tree.

\n
\n\n

Next, update the HeroesModule metadata.

\n\n\nimport { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule } from '@angular/forms';\n\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { HeroDetailComponent } from './hero-detail/hero-detail.component';\n\nimport { HeroesRoutingModule } from './heroes-routing.module';\n\n@NgModule({\n imports: [\n CommonModule,\n FormsModule,\n HeroesRoutingModule\n ],\n declarations: [\n HeroListComponent,\n HeroDetailComponent\n ]\n})\nexport class HeroesModule {}\n\n\n\n

The hero management file structure is as follows:

\n
\n
\n src/app/heroes\n
\n
\n
\n hero-detail\n
\n
\n
\n hero-detail.component.css\n
\n
\n hero-detail.component.html\n
\n
\n hero-detail.component.ts\n
\n
\n
\n hero-list\n
\n
\n
\n hero-list.component.css\n
\n
\n hero-list.component.html\n
\n
\n hero-list.component.ts\n
\n
\n
\n hero.service.ts\n
\n
\n hero.ts\n
\n
\n heroes-routing.module.ts\n
\n
\n heroes.module.ts\n
\n
\n mock-heroes.ts\n
\n
\n
\n
\n\n

Hero feature routing requirementslink

\n

The heroes feature has two interacting components, the hero list and the hero detail.\nWhen you navigate to list view, it gets a list of heroes and displays them.\nWhen you click on a hero, the detail view has to display that particular hero.

\n

You tell the detail view which hero to display by including the selected hero's id in the route URL.

\n

Import the hero components from their new locations in the src/app/heroes/ folder and define the two hero routes.

\n

Now that you have routes for the Heroes module, register them with the Router via the RouterModule as you did in the AppRoutingModule, with an important difference.

\n

In the AppRoutingModule, you used the static RouterModule.forRoot() method to register the routes and application level service providers.\nIn a feature module you use the static forChild() method.

\n
\n

Only call RouterModule.forRoot() in the root AppRoutingModule\n(or the AppModule if that's where you register top level application routes).\nIn any other module, you must call the RouterModule.forChild() method to register additional routes.

\n
\n

The updated HeroesRoutingModule looks like this:

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { HeroDetailComponent } from './hero-detail/hero-detail.component';\n\nconst heroesRoutes: Routes = [\n { path: 'heroes', component: HeroListComponent },\n { path: 'hero/:id', component: HeroDetailComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(heroesRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class HeroesRoutingModule { }\n\n\n
\n

Consider giving each feature module its own route configuration file.\nThough the feature routes are currently minimal, routes have a tendency to grow more complex even in small apps.

\n
\n\n

Remove duplicate hero routeslink

\n

The hero routes are currently defined in two places: in the HeroesRoutingModule,\nby way of the HeroesModule, and in the AppRoutingModule.

\n

Routes provided by feature modules are combined together into their imported module's routes by the router.\nThis allows you to continue defining the feature module routes without modifying the main route configuration.

\n

Remove the HeroListComponent import and the /heroes route from the app-routing.module.ts.

\n

Leave the default and the wildcard routes as these are still in use at the top level of the application.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\n// import { HeroListComponent } from './hero-list/hero-list.component'; // <-- delete this line\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nconst appRoutes: Routes = [\n { path: 'crisis-center', component: CrisisListComponent },\n // { path: 'heroes', component: HeroListComponent }, // <-- delete this line\n { path: '', redirectTo: '/heroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n )\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AppRoutingModule {}\n\n\n\n\n

Remove heroes declarationslink

\n

Because the HeroesModule now provides the HeroListComponent, remove it from the AppModule's declarations array.\nNow that you have a separate HeroesModule, you can evolve the hero feature with more components and different routes.

\n

After these steps, the AppModule should look like this:

\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { AppComponent } from './app.component';\nimport { AppRoutingModule } from './app-routing.module';\nimport { HeroesModule } from './heroes/heroes.module';\n\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n FormsModule,\n HeroesModule,\n AppRoutingModule\n ],\n declarations: [\n AppComponent,\n CrisisListComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n

Module import orderlink

\n

Notice that in the module imports array, the AppRoutingModule is last and comes after the HeroesModule.

\n\nimports: [\n BrowserModule,\n FormsModule,\n HeroesModule,\n AppRoutingModule\n],\n\n\n

The order of route configuration is important because the router accepts the first route that matches a navigation request path.

\n

When all routes were in one AppRoutingModule, you put the default and wildcard routes last, after the /heroes route, so that the router had a chance to match a URL to the /heroes route before hitting the wildcard route and navigating to \"Page not found\".

\n

Each routing module augments the route configuration in the order of import.\nIf you listed AppRoutingModule first, the wildcard route would be registered before the hero routes.\nThe wildcard route—which matches every URL—would intercept the attempt to navigate to a hero route.

\n
\n

Reverse the routing modules to see a click of the heroes link resulting in \"Page not found\".\nLearn about inspecting the runtime router configuration below.

\n
\n

Route Parameterslink

\n\n

Route definition with a parameterlink

\n

Return to the HeroesRoutingModule and look at the route definitions again.\nThe route to HeroDetailComponent has an :id token in the path.

\n\n{ path: 'hero/:id', component: HeroDetailComponent }\n\n\n

The :id token creates a slot in the path for a Route Parameter.\nIn this case, this configuration causes the router to insert the id of a hero into that slot.

\n

If you tell the router to navigate to the detail component and display \"Magneta\", you expect a hero id to appear in the browser URL like this:

\n\n localhost:4200/hero/15\n\n\n

If a user enters that URL into the browser address bar, the router should recognize the pattern and go to the same \"Magneta\" detail view.

\n
\n
\n Route parameter: Required or optional?\n
\n

Embedding the route parameter token, :id, in the route definition path is a good choice for this scenario because the id is required by the HeroDetailComponent and because the value 15 in the path clearly distinguishes the route to \"Magneta\" from a route for some other hero.

\n
\n\n

Setting the route parameters in the list viewlink

\n

After navigating to the HeroDetailComponent, you expect to see the details of the selected hero.\nYou need two pieces of information: the routing path to the component and the hero's id.

\n

Accordingly, the link parameters array has two items: the routing path and a route parameter that specifies the\nid of the selected hero.

\n\n<a [routerLink]=\"['/hero', hero.id]\">\n\n\n

The router composes the destination URL from the array like this: localhost:4200/hero/15.

\n

The router extracts the route parameter (id:15) from the URL and supplies it to\nthe HeroDetailComponent via the ActivatedRoute service.

\n\n

Activated Route in actionlink

\n

Import the Router, ActivatedRoute, and ParamMap tokens from the router package.

\n\nimport { Router, ActivatedRoute, ParamMap } from '@angular/router';\n\n\n

Import the switchMap operator because you need it later to process the Observable route parameters.

\n\nimport { switchMap } from 'rxjs/operators';\n\n\n\n

Add the services as private variables to the constructor so that Angular injects them (makes them visible to the component).

\n\nconstructor(\n private route: ActivatedRoute,\n private router: Router,\n private service: HeroService\n) {}\n\n\n

In the ngOnInit() method, use the ActivatedRoute service to retrieve the parameters for the route, pull the hero id from the parameters, and retrieve the hero to display.

\n\nngOnInit() {\n this.hero$ = this.route.paramMap.pipe(\n switchMap((params: ParamMap) =>\n this.service.getHero(params.get('id')))\n );\n}\n\n\n

When the map changes, paramMap gets the id parameter from the changed parameters.

\n

Then you tell the HeroService to fetch the hero with that id and return the result of the HeroService request.

\n

The switchMap operator does two things. It flattens the Observable<Hero> that HeroService returns and cancels previous pending requests.\nIf the user re-navigates to this route with a new id while the HeroService is still retrieving the old id, switchMap discards that old request and returns the hero for the new id.

\n

AsyncPipe handles the observable subscription and the component's hero property will be (re)set with the retrieved hero.

\n

ParamMap APIlink

\n

The ParamMap API is inspired by the URLSearchParams interface.\nIt provides methods to handle parameter access for both route parameters (paramMap) and query parameters (queryParamMap).

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Member\n \n Description\n
\n has(name)\n \n

Returns true if the parameter name is in the map of parameters.

\n
\n get(name)\n \n

Returns the parameter name value (a string) if present, or null if the parameter name is not in the map. Returns the first element if the parameter value is actually an array of values.

\n
\n getAll(name)\n \n

Returns a string array of the parameter name value if found, or an empty array if the parameter name value is not in the map. Use getAll when a single parameter could have multiple values.

\n
\n keys\n \n

Returns a string array of all parameter names in the map.

\n
\n\n

Observable paramMap and component reuselink

\n

In this example, you retrieve the route parameter map from an Observable.\nThat implies that the route parameter map can change during the lifetime of this component.

\n

By default, the router re-uses a component instance when it re-navigates to the same component type\nwithout visiting a different component first. The route parameters could change each time.

\n

Suppose a parent component navigation bar had \"forward\" and \"back\" buttons\nthat scrolled through the list of heroes.\nEach click navigated imperatively to the HeroDetailComponent with the next or previous id.

\n

You wouldn't want the router to remove the current HeroDetailComponent instance from the DOM only to re-create it for the next id as this would re-render the view.\nFor better UX, the router re-uses the same component instance and updates the parameter.

\n

Since ngOnInit() is only called once per component instantiation, you can detect when the route parameters change from within the same instance using the observable paramMap property.

\n
\n

When subscribing to an observable in a component, you almost always unsubscribe when the component is destroyed.

\n

However, ActivatedRoute observables are among the exceptions because ActivatedRoute and its observables are insulated from the Router itself.\nThe Router destroys a routed component when it is no longer needed along with the injected ActivatedRoute.

\n
\n\n

snapshot: the no-observable alternativelink

\n

This application won't re-use the HeroDetailComponent.\nThe user always returns to the hero list to select another hero to view.\nThere's no way to navigate from one hero detail to another hero detail without visiting the list component in between.\nTherefore, the router creates a new HeroDetailComponent instance every time.

\n

When you know for certain that a HeroDetailComponent instance will never be re-used, you can use snapshot.

\n

route.snapshot provides the initial value of the route parameter map.\nYou can access the parameters directly without subscribing or adding observable operators as in the following:

\n\nngOnInit() {\n const id = this.route.snapshot.paramMap.get('id');\n\n this.hero$ = this.service.getHero(id);\n}\n\n\n
\n

snapshot only gets the initial value of the parameter map with this technique.\nUse the observable paramMap approach if there's a possibility that the router could re-use the component.\nThis tutorial sample app uses with the observable paramMap.

\n
\n\n

Navigating back to the list componentlink

\n

The HeroDetailComponent \"Back\" button uses the gotoHeroes() method that navigates imperatively back to the HeroListComponent.

\n

The router navigate() method takes the same one-item link parameters array that you can bind to a [routerLink] directive.\nIt holds the path to the HeroListComponent:

\n\ngotoHeroes() {\n this.router.navigate(['/heroes']);\n}\n\n\n\n

Route Parameters: Required or optional?link

\n

Use route parameters to specify a required parameter value within the route URL\nas you do when navigating to the HeroDetailComponent in order to view the hero with id 15:

\n\n localhost:4200/hero/15\n\n\n

You can also add optional information to a route request.\nFor example, when returning to the hero-detail.component.ts list from the hero detail view, it would be nice if the viewed hero were preselected in the list.

\n
\n \"Selected\n
\n

You implement this feature by including the viewed hero's id in the URL as an optional parameter when returning from the HeroDetailComponent.

\n

Optional information can also include other forms such as:

\n\n

As these kinds of parameters don't fit easily in a URL path, you can use optional parameters for conveying arbitrarily complex information during navigation.\nOptional parameters aren't involved in pattern matching and afford flexibility of expression.

\n

The router supports navigation with optional parameters as well as required route parameters.\nDefine optional parameters in a separate object after you define the required route parameters.

\n

In general, use a required route parameter when the value is mandatory (for example, if necessary to distinguish one route path from another); and an optional parameter when the value is optional, complex, and/or multivariate.

\n\n

Heroes list: optionally selecting a herolink

\n

When navigating to the HeroDetailComponent you specified the required id of the hero-to-edit in the\nroute parameter and made it the second item of the link parameters array.

\n\n<a [routerLink]=\"['/hero', hero.id]\">\n\n\n

The router embedded the id value in the navigation URL because you had defined it as a route parameter with an :id placeholder token in the route path:

\n\n{ path: 'hero/:id', component: HeroDetailComponent }\n\n\n

When the user clicks the back button, the HeroDetailComponent constructs another link parameters array\nwhich it uses to navigate back to the HeroListComponent.

\n\ngotoHeroes() {\n this.router.navigate(['/heroes']);\n}\n\n\n

This array lacks a route parameter because previously you didn't need to send information to the HeroListComponent.

\n

Now, send the id of the current hero with the navigation request so that the\nHeroListComponent can highlight that hero in its list.

\n

Send the id with an object that contains an optional id parameter.\nFor demonstration purposes, there's an extra junk parameter (foo) in the object that the HeroListComponent should ignore.\nHere's the revised navigation statement:

\n\ngotoHeroes(hero: Hero) {\n const heroId = hero ? hero.id : null;\n // Pass along the hero id if available\n // so that the HeroList component can select that hero.\n // Include a junk 'foo' property for fun.\n this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);\n}\n\n\n

The application still works. Clicking \"back\" returns to the hero list view.

\n

Look at the browser address bar.

\n

It should look something like this, depending on where you run it:

\n\n localhost:4200/heroes;id=15;foo=foo\n\n\n

The id value appears in the URL as (;id=15;foo=foo), not in the URL path.\nThe path for the \"Heroes\" route doesn't have an :id token.

\n

The optional route parameters are not separated by \"?\" and \"&\" as they would be in the URL query string.\nThey are separated by semicolons \";\".\nThis is matrix URL notation.

\n
\n

Matrix URL notation is an idea first introduced in a 1996 proposal by the founder of the web, Tim Berners-Lee.

\n

Although matrix notation never made it into the HTML standard, it is legal and it became popular among browser routing systems as a way to isolate parameters belonging to parent and child routes.\nAs such, the Router provides support for the matrix notation across browsers.

\n
\n\n

Route parameters in the ActivatedRoute servicelink

\n

In its current state of development, the list of heroes is unchanged.\nNo hero row is highlighted.

\n

The HeroListComponent needs code that expects parameters.

\n

Previously, when navigating from the HeroListComponent to the HeroDetailComponent,\nyou subscribed to the route parameter map Observable and made it available to the HeroDetailComponent\nin the ActivatedRoute service.\nYou injected that service in the constructor of the HeroDetailComponent.

\n

This time you'll be navigating in the opposite direction, from the HeroDetailComponent to the HeroListComponent.

\n

First, extend the router import statement to include the ActivatedRoute service symbol:

\n\nimport { ActivatedRoute } from '@angular/router';\n\n\n

Import the switchMap operator to perform an operation on the Observable of route parameter map.

\n\nimport { Observable } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\n\n\n

Inject the ActivatedRoute in the HeroListComponent constructor.

\n\nexport class HeroListComponent implements OnInit {\n heroes$: Observable<Hero[]>;\n selectedId: number;\n\n constructor(\n private service: HeroService,\n private route: ActivatedRoute\n ) {}\n\n ngOnInit() {\n this.heroes$ = this.route.paramMap.pipe(\n switchMap(params => {\n // (+) before `params.get()` turns the string into a number\n this.selectedId = +params.get('id');\n return this.service.getHeroes();\n })\n );\n }\n}\n\n\n

The ActivatedRoute.paramMap property is an Observable map of route parameters.\nThe paramMap emits a new map of values that includes id when the user navigates to the component.\nIn ngOnInit() you subscribe to those values, set the selectedId, and get the heroes.

\n

Update the template with a class binding.\nThe binding adds the selected CSS class when the comparison returns true and removes it when false.\nLook for it within the repeated <li> tag as shown here:

\n\n<h2>HEROES</h2>\n<ul class=\"heroes\">\n <li *ngFor=\"let hero of heroes$ | async\"\n [class.selected]=\"hero.id === selectedId\">\n <a [routerLink]=\"['/hero', hero.id]\">\n <span class=\"badge\">{{ hero.id }}</span>{{ hero.name }}\n </a>\n </li>\n</ul>\n\n<button routerLink=\"/sidekicks\">Go to sidekicks</button>\n\n\n

Add some styles to apply when the list item is selected.

\n\n.heroes li.selected {\n background-color: #CFD8DC;\n color: white;\n}\n.heroes li.selected:hover {\n background-color: #BBD8DC;\n}\n\n\n

When the user navigates from the heroes list to the \"Magneta\" hero and back, \"Magneta\" appears selected:

\n
\n \"Selected\n
\n

The optional foo route parameter is harmless and the router continues to ignore it.

\n\n

Adding routable animationslink

\n

This section shows you how to add some animations to the HeroDetailComponent.

\n

First, import the BrowserAnimationsModule and add it to the imports array:

\n\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n\n@NgModule({\n imports: [\n BrowserAnimationsModule,\n ],\n})\n\n\n

Next, add a data object to the routes for HeroListComponent and HeroDetailComponent.\nTransitions are based on states and you use the animation data from the route to provide a named animation state for the transitions.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { HeroDetailComponent } from './hero-detail/hero-detail.component';\n\nconst heroesRoutes: Routes = [\n { path: 'heroes', component: HeroListComponent, data: { animation: 'heroes' } },\n { path: 'hero/:id', component: HeroDetailComponent, data: { animation: 'hero' } }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(heroesRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class HeroesRoutingModule { }\n\n\n

Create an animations.ts file in the root src/app/ folder. The contents look like this:

\n\nimport {\n trigger, animateChild, group,\n transition, animate, style, query\n} from '@angular/animations';\n\n\n// Routable animations\nexport const slideInAnimation =\n trigger('routeAnimation', [\n transition('heroes <=> hero', [\n style({ position: 'relative' }),\n query(':enter, :leave', [\n style({\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%'\n })\n ]),\n query(':enter', [\n style({ left: '-100%'})\n ]),\n query(':leave', animateChild()),\n group([\n query(':leave', [\n animate('300ms ease-out', style({ left: '100%'}))\n ]),\n query(':enter', [\n animate('300ms ease-out', style({ left: '0%'}))\n ])\n ]),\n query(':enter', animateChild()),\n ])\n ]);\n\n\n\n

This file does the following:

\n\n

Back in the AppComponent, import the RouterOutlet token from the @angular/router package and the slideInAnimation from './animations.ts.

\n

Add an animations array to the @Component metadata that contains the slideInAnimation.

\n\nimport { RouterOutlet } from '@angular/router';\nimport { slideInAnimation } from './animations';\n\n@Component({\n selector: 'app-root',\n templateUrl: 'app.component.html',\n styleUrls: ['app.component.css'],\n animations: [ slideInAnimation ]\n})\n\n\n

In order to use the routable animations, wrap the RouterOutlet inside an element, use the @routeAnimation trigger, and bind it to the element.

\n

For the @routeAnimation transitions to key off states, provide it with the data from the ActivatedRoute.\nThe RouterOutlet is exposed as an outlet template variable, so you bind a reference to the router outlet.\nThis example uses a variable of routerOutlet.

\n\n<h1>Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/heroes\" routerLinkActive=\"active\">Heroes</a>\n</nav>\n<div [@routeAnimation]=\"getAnimationData(routerOutlet)\">\n <router-outlet #routerOutlet=\"outlet\"></router-outlet>\n</div>\n\n\n

The @routeAnimation property is bound to the getAnimationData() with the provided routerOutlet reference, so the next step is to define that function in the AppComponent.\nThe getAnimationData() function returns the animation property from the data provided through the ActivatedRoute. The animation property matches the transition names you used in the slideInAnimation defined in animations.ts.

\n\nexport class AppComponent {\n getAnimationData(outlet: RouterOutlet) {\n return outlet && outlet.activatedRouteData && outlet.activatedRouteData.animation;\n }\n}\n\n\n

When switching between the two routes, the HeroDetailComponent and HeroListComponent now ease in from the left when routed to and will slide to the right when navigating away.

\n\n

Milestone 3 wrap uplink

\n

This section has covered the following:

\n\n

After these changes, the folder structure is as follows:

\n
\n
\n angular-router-sample\n
\n
\n
\n src\n
\n
\n
\n app\n
\n
\n
\n crisis-list\n
\n
\n
\n crisis-list.component.css\n
\n
\n crisis-list.component.html\n
\n
\n crisis-list.component.ts\n
\n
\n
\n heroes\n
\n
\n
\n hero-detail\n
\n
\n
\n hero-detail.component.css\n
\n
\n hero-detail.component.html\n
\n
\n hero-detail.component.ts\n
\n
\n
\n hero-list\n
\n
\n
\n hero-list.component.css\n
\n
\n hero-list.component.html\n
\n
\n hero-list.component.ts\n
\n
\n
\n hero.service.ts\n
\n
\n hero.ts\n
\n
\n heroes-routing.module.ts\n
\n
\n heroes.module.ts\n
\n
\n mock-heroes.ts\n
\n
\n
\n page-not-found\n
\n
\n
\n

page-not-found.component.css

\n
\n
\n

page-not-found.component.html

\n
\n
\n

page-not-found.component.ts

\n
\n
\n
\n
\n animations.ts\n
\n
\n app.component.css\n
\n
\n app.component.html\n
\n
\n app.component.ts\n
\n
\n app.module.ts\n
\n
\n app-routing.module.ts\n
\n
\n main.ts\n
\n
\n message.service.ts\n
\n
\n index.html\n
\n
\n styles.css\n
\n
\n tsconfig.json\n
\n
\n
\n node_modules ...\n
\n
\n package.json\n
\n
\n
\n

Here are the relevant files for this version of the sample application.

\n\n\n \nimport {\n trigger, animateChild, group,\n transition, animate, style, query\n} from '@angular/animations';\n\n\n// Routable animations\nexport const slideInAnimation =\n trigger('routeAnimation', [\n transition('heroes <=> hero', [\n style({ position: 'relative' }),\n query(':enter, :leave', [\n style({\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%'\n })\n ]),\n query(':enter', [\n style({ left: '-100%'})\n ]),\n query(':leave', animateChild()),\n group([\n query(':leave', [\n animate('300ms ease-out', style({ left: '100%'}))\n ]),\n query(':enter', [\n animate('300ms ease-out', style({ left: '0%'}))\n ])\n ]),\n query(':enter', animateChild()),\n ])\n ]);\n\n\n\n\n \n<h1>Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/heroes\" routerLinkActive=\"active\">Heroes</a>\n</nav>\n<div [@routeAnimation]=\"getAnimationData(routerOutlet)\">\n <router-outlet #routerOutlet=\"outlet\"></router-outlet>\n</div>\n\n\n\n \nimport { Component } from '@angular/core';\nimport { RouterOutlet } from '@angular/router';\nimport { slideInAnimation } from './animations';\n\n@Component({\n selector: 'app-root',\n templateUrl: 'app.component.html',\n styleUrls: ['app.component.css'],\n animations: [ slideInAnimation ]\n})\nexport class AppComponent {\n getAnimationData(outlet: RouterOutlet) {\n return outlet && outlet.activatedRouteData && outlet.activatedRouteData.animation;\n }\n}\n\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n\nimport { AppComponent } from './app.component';\nimport { AppRoutingModule } from './app-routing.module';\nimport { HeroesModule } from './heroes/heroes.module';\n\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n FormsModule,\n HeroesModule,\n AppRoutingModule\n ],\n declarations: [\n AppComponent,\n CrisisListComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\n/* . . . */\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nconst appRoutes: Routes = [\n { path: 'crisis-center', component: CrisisListComponent },\n/* . . . */\n { path: '', redirectTo: '/heroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n )\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AppRoutingModule {}\n\n\n\n \n/* HeroListComponent's private CSS styles */\n.heroes {\n margin: 0 0 2em 0;\n list-style-type: none;\n padding: 0;\n width: 15em;\n}\n.heroes li {\n position: relative;\n cursor: pointer;\n background-color: #EEE;\n margin: .5em;\n padding: .3em 0;\n height: 1.6em;\n border-radius: 4px;\n}\n\n.heroes li:hover {\n color: #607D8B;\n background-color: #DDD;\n left: .1em;\n}\n\n.heroes a {\n color: #888;\n text-decoration: none;\n position: relative;\n display: block;\n}\n\n.heroes a:hover {\n color:#607D8B;\n}\n\n.heroes .badge {\n display: inline-block;\n font-size: small;\n color: white;\n padding: 0.8em 0.7em 0 0.7em;\n background-color: #607D8B;\n line-height: 1em;\n position: relative;\n left: -1px;\n top: -4px;\n height: 1.8em;\n min-width: 16px;\n text-align: right;\n margin-right: .8em;\n border-radius: 4px 0 0 4px;\n}\n\nbutton {\n background-color: #eee;\n border: none;\n padding: 5px 10px;\n border-radius: 4px;\n cursor: pointer;\n font-family: Arial, sans-serif;\n}\n\nbutton:hover {\n background-color: #cfd8dc;\n}\n\nbutton.delete {\n position: relative;\n left: 194px;\n top: -32px;\n background-color: gray !important;\n color: white;\n}\n\n.heroes li.selected {\n background-color: #CFD8DC;\n color: white;\n}\n.heroes li.selected:hover {\n background-color: #BBD8DC;\n}\n\n\n\n\n \n<h2>HEROES</h2>\n<ul class=\"heroes\">\n <li *ngFor=\"let hero of heroes$ | async\"\n [class.selected]=\"hero.id === selectedId\">\n <a [routerLink]=\"['/hero', hero.id]\">\n <span class=\"badge\">{{ hero.id }}</span>{{ hero.name }}\n </a>\n </li>\n</ul>\n\n<button routerLink=\"/sidekicks\">Go to sidekicks</button>\n\n\n\n \n// TODO: Feature Componetized like CrisisCenter\nimport { Observable } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\nimport { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\n\nimport { HeroService } from '../hero.service';\nimport { Hero } from '../hero';\n\n@Component({\n selector: 'app-hero-list',\n templateUrl: './hero-list.component.html',\n styleUrls: ['./hero-list.component.css']\n})\nexport class HeroListComponent implements OnInit {\n heroes$: Observable<Hero[]>;\n selectedId: number;\n\n constructor(\n private service: HeroService,\n private route: ActivatedRoute\n ) {}\n\n ngOnInit() {\n this.heroes$ = this.route.paramMap.pipe(\n switchMap(params => {\n // (+) before `params.get()` turns the string into a number\n this.selectedId = +params.get('id');\n return this.service.getHeroes();\n })\n );\n }\n}\n\n\n\n\n \n<h2>HEROES</h2>\n<div *ngIf=\"hero$ | async as hero\">\n <h3>\"{{ hero.name }}\"</h3>\n <div>\n <label>Id: </label>{{ hero.id }}</div>\n <div>\n <label>Name: </label>\n <input [(ngModel)]=\"hero.name\" placeholder=\"name\"/>\n </div>\n <p>\n <button (click)=\"gotoHeroes(hero)\">Back</button>\n </p>\n</div>\n\n\n\n \nimport { switchMap } from 'rxjs/operators';\nimport { Component, OnInit } from '@angular/core';\nimport { Router, ActivatedRoute, ParamMap } from '@angular/router';\nimport { Observable } from 'rxjs';\n\nimport { HeroService } from '../hero.service';\nimport { Hero } from '../hero';\n\n@Component({\n selector: 'app-hero-detail',\n templateUrl: './hero-detail.component.html',\n styleUrls: ['./hero-detail.component.css']\n})\nexport class HeroDetailComponent implements OnInit {\n hero$: Observable<Hero>;\n\n constructor(\n private route: ActivatedRoute,\n private router: Router,\n private service: HeroService\n ) {}\n\n ngOnInit() {\n this.hero$ = this.route.paramMap.pipe(\n switchMap((params: ParamMap) =>\n this.service.getHero(params.get('id')))\n );\n }\n\n gotoHeroes(hero: Hero) {\n const heroId = hero ? hero.id : null;\n // Pass along the hero id if available\n // so that the HeroList component can select that hero.\n // Include a junk 'foo' property for fun.\n this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);\n }\n}\n\n\n\n\n \nimport { Injectable } from '@angular/core';\n\nimport { Observable, of } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nimport { Hero } from './hero';\nimport { HEROES } from './mock-heroes';\nimport { MessageService } from '../message.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class HeroService {\n\n constructor(private messageService: MessageService) { }\n\n getHeroes(): Observable<Hero[]> {\n // TODO: send the message _after_ fetching the heroes\n this.messageService.add('HeroService: fetched heroes');\n return of(HEROES);\n }\n\n getHero(id: number | string) {\n return this.getHeroes().pipe(\n // (+) before `id` turns the string into a number\n map((heroes: Hero[]) => heroes.find(hero => hero.id === +id))\n );\n }\n}\n\n\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule } from '@angular/forms';\n\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { HeroDetailComponent } from './hero-detail/hero-detail.component';\n\nimport { HeroesRoutingModule } from './heroes-routing.module';\n\n@NgModule({\n imports: [\n CommonModule,\n FormsModule,\n HeroesRoutingModule\n ],\n declarations: [\n HeroListComponent,\n HeroDetailComponent\n ]\n})\nexport class HeroesModule {}\n\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { HeroDetailComponent } from './hero-detail/hero-detail.component';\n\nconst heroesRoutes: Routes = [\n { path: 'heroes', component: HeroListComponent, data: { animation: 'heroes' } },\n { path: 'hero/:id', component: HeroDetailComponent, data: { animation: 'hero' } }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(heroesRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class HeroesRoutingModule { }\n\n\n\n \nimport { Injectable } from '@angular/core';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class MessageService {\n messages: string[] = [];\n\n add(message: string) {\n this.messages.push(message);\n }\n\n clear() {\n this.messages = [];\n }\n}\n\n\n\n\n\n\n

Milestone 4: Crisis center featurelink

\n

This section shows you how to add child routes and use relative routing in your app.

\n

To add more features to the app's current crisis center, take similar steps as for the heroes feature:

\n\n

Use mock crises instead of mock heroes:

\n\nimport { Crisis } from './crisis';\n\nexport const CRISES: Crisis[] = [\n { id: 1, name: 'Dragon Burning Cities' },\n { id: 2, name: 'Sky Rains Great White Sharks' },\n { id: 3, name: 'Giant Asteroid Heading For Earth' },\n { id: 4, name: 'Procrastinators Meeting Delayed Again' },\n];\n\n\n\n

The resulting crisis center is a foundation for introducing a new concept—child routing.\nYou can leave Heroes in its current state as a contrast with the Crisis Center.

\n
\n

In keeping with the Separation of Concerns principle, changes to the Crisis Center don't affect the AppModule or any other feature's component.

\n
\n\n

A crisis center with child routeslink

\n

This section shows you how to organize the crisis center to conform to the following recommended pattern for Angular applications:

\n\n

If your app had many feature areas, the app component trees might look like this:

\n
\n \"Component\n
\n\n

Child routing componentlink

\n

Generate a CrisisCenter component in the crisis-center folder:

\n\n ng generate component crisis-center/crisis-center\n\n

Update the component template with the following markup:

\n\n<h2>CRISIS CENTER</h2>\n<router-outlet></router-outlet>\n\n\n

The CrisisCenterComponent has the following in common with the AppComponent:

\n\n

Like most shells, the CrisisCenterComponent class is minimal because it has no business logic, and its template has no links, just a title and <router-outlet> for the crisis center child component.

\n\n

Child route configurationlink

\n

As a host page for the \"Crisis Center\" feature, generate a CrisisCenterHome component in the crisis-center folder.

\n\n ng generate component crisis-center/crisis-center-home\n\n

Update the template with a welcome message to the Crisis Center.

\n\n<p>Welcome to the Crisis Center</p>\n\n\n

Update the crisis-center-routing.module.ts you renamed after copying it from heroes-routing.module.ts file.\nThis time, you define child routes within the parent crisis-center route.

\n\nconst crisisCenterRoutes: Routes = [\n {\n path: 'crisis-center',\n component: CrisisCenterComponent,\n children: [\n {\n path: '',\n component: CrisisListComponent,\n children: [\n {\n path: ':id',\n component: CrisisDetailComponent\n },\n {\n path: '',\n component: CrisisCenterHomeComponent\n }\n ]\n }\n ]\n }\n];\n\n\n

Notice that the parent crisis-center route has a children property with a single route containing the CrisisListComponent.\nThe CrisisListComponent route also has a children array with two routes.

\n

These two routes navigate to the crisis center child components,\nCrisisCenterHomeComponent and CrisisDetailComponent, respectively.

\n

There are important differences in the way the router treats child routes.

\n

The router displays the components of these routes in the RouterOutlet of the CrisisCenterComponent, not in the RouterOutlet of the AppComponent shell.

\n

The CrisisListComponent contains the crisis list and a RouterOutlet to display the Crisis Center Home and Crisis Detail route components.

\n

The Crisis Detail route is a child of the Crisis List.\nThe router reuses components by default, so the Crisis Detail component will be re-used as you select different crises.\nIn contrast, back in the Hero Detail route, the component was recreated each time you selected a different hero from the list of heroes.

\n

At the top level, paths that begin with / refer to the root of the application.\nBut child routes extend the path of the parent route.\nWith each step down the route tree,\nyou add a slash followed by the route path, unless the path is empty.

\n

Apply that logic to navigation within the crisis center for which the parent path is /crisis-center.

\n\n

The absolute URL for the latter example, including the localhost origin, is as follows:

\n\n localhost:4200/crisis-center/2\n\n\n

Here's the complete crisis-center-routing.module.ts file with its imports.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { CrisisCenterComponent } from './crisis-center/crisis-center.component';\nimport { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';\n\nconst crisisCenterRoutes: Routes = [\n {\n path: 'crisis-center',\n component: CrisisCenterComponent,\n children: [\n {\n path: '',\n component: CrisisListComponent,\n children: [\n {\n path: ':id',\n component: CrisisDetailComponent\n },\n {\n path: '',\n component: CrisisCenterHomeComponent\n }\n ]\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(crisisCenterRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class CrisisCenterRoutingModule { }\n\n\n\n

Import crisis center module into the AppModule routeslink

\n

As with the HeroesModule, you must add the CrisisCenterModule to the imports array of the AppModule\nbefore the AppRoutingModule:

\n\n\n \nimport { NgModule } from '@angular/core';\nimport { FormsModule } from '@angular/forms';\nimport { CommonModule } from '@angular/common';\n\nimport { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { CrisisCenterComponent } from './crisis-center/crisis-center.component';\nimport { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';\n\nimport { CrisisCenterRoutingModule } from './crisis-center-routing.module';\n\n@NgModule({\n imports: [\n CommonModule,\n FormsModule,\n CrisisCenterRoutingModule\n ],\n declarations: [\n CrisisCenterComponent,\n CrisisListComponent,\n CrisisCenterHomeComponent,\n CrisisDetailComponent\n ]\n})\nexport class CrisisCenterModule {}\n\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule } from '@angular/forms';\n\nimport { AppComponent } from './app.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\nimport { ComposeMessageComponent } from './compose-message/compose-message.component';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { HeroesModule } from './heroes/heroes.module';\nimport { CrisisCenterModule } from './crisis-center/crisis-center.module';\n\n@NgModule({\n imports: [\n CommonModule,\n FormsModule,\n HeroesModule,\n CrisisCenterModule,\n AppRoutingModule\n ],\n declarations: [\n AppComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n\n

Remove the initial crisis center route from the app-routing.module.ts because now the HeroesModule and the CrisisCenter modules provide the feature routes.

\n

The app-routing.module.ts file retains the top-level application routes such as the default and wildcard routes.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nconst appRoutes: Routes = [\n { path: '', redirectTo: '/heroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forRoot(\n appRoutes,\n { enableTracing: true } // <-- debugging purposes only\n )\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AppRoutingModule {}\n\n\n\n\n

Relative navigationlink

\n

While building out the crisis center feature, you navigated to the\ncrisis detail route using an absolute path that begins with a slash.

\n

The router matches such absolute paths to routes starting from the top of the route configuration.

\n

You could continue to use absolute paths like this to navigate inside the Crisis Center feature, but that pins the links to the parent routing structure.\nIf you changed the parent /crisis-center path, you would have to change the link parameters array.

\n

You can free the links from this dependency by defining paths that are relative to the current URL segment.\nNavigation within the feature area remains intact even if you change the parent route path to the feature.

\n
\n

The router supports directory-like syntax in a link parameters list to help guide route name lookup:

\n

./ or no leading slash is relative to the current level.

\n

../ to go up one level in the route path.

\n

You can combine relative navigation syntax with an ancestor path.\nIf you must navigate to a sibling route, you could use the ../<sibling> convention to go up\none level, then over and down the sibling route path.

\n
\n

To navigate a relative path with the Router.navigate method, you must supply the ActivatedRoute\nto give the router knowledge of where you are in the current route tree.

\n

After the link parameters array, add an object with a relativeTo property set to the ActivatedRoute.\nThe router then calculates the target URL based on the active route's location.

\n
\n

Always specify the complete absolute path when calling router's navigateByUrl() method.

\n
\n\n

Navigate to crisis list with a relative URLlink

\n

You've already injected the ActivatedRoute that you need to compose the relative navigation path.

\n

When using a RouterLink to navigate instead of the Router service, you'd use the same link parameters array, but you wouldn't provide the object with the relativeTo property.\nThe ActivatedRoute is implicit in a RouterLink directive.

\n

Update the gotoCrises() method of the CrisisDetailComponent to navigate back to the Crisis Center list using relative path navigation.

\n\n// Relative navigation back to the crises\nthis.router.navigate(['../', { id: crisisId, foo: 'foo' }], { relativeTo: this.route });\n\n\n

Notice that the path goes up a level using the ../ syntax.\nIf the current crisis id is 3, the resulting path back to the crisis list is /crisis-center/;id=3;foo=foo.

\n\n

Displaying multiple routes in named outletslink

\n

You decide to give users a way to contact the crisis center.\nWhen a user clicks a \"Contact\" button, you want to display a message in a popup view.

\n

The popup should stay open, even when switching between pages in the application, until the user closes it\nby sending the message or canceling.\nClearly you can't put the popup in the same outlet as the other pages.

\n

Until now, you've defined a single outlet and you've nested child routes under that outlet to group routes together.\nThe router only supports one primary unnamed outlet per template.

\n

A template can also have any number of named outlets.\nEach named outlet has its own set of routes with their own components.\nMultiple outlets can display different content, determined by different routes, all at the same time.

\n

Add an outlet named \"popup\" in the AppComponent, directly below the unnamed outlet.

\n\n<div [@routeAnimation]=\"getAnimationData(routerOutlet)\">\n <router-outlet #routerOutlet=\"outlet\"></router-outlet>\n</div>\n<router-outlet name=\"popup\"></router-outlet>\n\n\n

That's where a popup will go, once you learn how to route a popup component to it.

\n\n

Secondary routeslink

\n

Named outlets are the targets of secondary routes.

\n

Secondary routes look like primary routes and you configure them the same way.\nThey differ in a few key respects.

\n\n

Generate a new component to compose the message.

\n\n ng generate component compose-message\n\n

It displays a short form with a header, an input box for the message,\nand two buttons, \"Send\" and \"Cancel\".

\n
\n \"Contact\n
\n

Here's the component, its template and styles:

\n\n\n \n:host {\n position: relative; bottom: 10%;\n}\n\n\n\n \n<h3>Contact Crisis Center</h3>\n<div *ngIf=\"details\">\n {{ details }}\n</div>\n<div>\n <div>\n <label>Message: </label>\n </div>\n <div>\n <textarea [(ngModel)]=\"message\" rows=\"10\" cols=\"35\" [disabled]=\"sending\"></textarea>\n </div>\n</div>\n<p *ngIf=\"!sending\">\n <button (click)=\"send()\">Send</button>\n <button (click)=\"cancel()\">Cancel</button>\n</p>\n\n\n\n\n \nimport { Component, HostBinding } from '@angular/core';\nimport { Router } from '@angular/router';\n\n@Component({\n selector: 'app-compose-message',\n templateUrl: './compose-message.component.html',\n styleUrls: ['./compose-message.component.css']\n})\nexport class ComposeMessageComponent {\n details: string;\n message: string;\n sending = false;\n\n constructor(private router: Router) {}\n\n send() {\n this.sending = true;\n this.details = 'Sending Message...';\n\n setTimeout(() => {\n this.sending = false;\n this.closePopup();\n }, 1000);\n }\n\n cancel() {\n this.closePopup();\n }\n\n closePopup() {\n // Providing a `null` value to the named outlet\n // clears the contents of the named outlet\n this.router.navigate([{ outlets: { popup: null }}]);\n }\n}\n\n\n\n\n\n

It looks similar to any other component in this guide, but there are two key differences.

\n

Note that the send() method simulates latency by waiting a second before \"sending\" the message and closing the popup.

\n

The closePopup() method closes the popup view by navigating to the popup outlet with a null which the section on clearing secondary routes covers.

\n\n

Add a secondary routelink

\n

Open the AppRoutingModule and add a new compose route to the appRoutes.

\n\n{\n path: 'compose',\n component: ComposeMessageComponent,\n outlet: 'popup'\n},\n\n\n

In addition to the path and component properties, there's a new property called outlet, which is set to 'popup'.\nThis route now targets the popup outlet and the ComposeMessageComponent will display there.

\n

To give users a way to open the popup, add a \"Contact\" link to the AppComponent template.

\n\n<a [routerLink]=\"[{ outlets: { popup: ['compose'] } }]\">Contact</a>\n\n\n

Although the compose route is configured to the \"popup\" outlet, that's not sufficient for connecting the route to a RouterLink directive.\nYou have to specify the named outlet in a link parameters array and bind it to the RouterLink with a property binding.

\n

The link parameters array contains an object with a single outlets property whose value is another object keyed by one (or more) outlet names.\nIn this case there is only the \"popup\" outlet property and its value is another link parameters array that specifies the compose route.

\n

In other words, when the user clicks this link, the router displays the component associated with the compose route in the popup outlet.

\n
\n

This outlets object within an outer object was unnecessary when there was only one route and one unnamed outlet.

\n

The router assumed that your route specification targeted the unnamed primary outlet and created these objects for you.

\n

Routing to a named outlet has revealed a router feature:\nyou can target multiple outlets with multiple routes in the same RouterLink directive.

\n
\n\n

Secondary route navigation: merging routes during navigationlink

\n

Navigate to the Crisis Center and click \"Contact\".\nyou should see something like the following URL in the browser address bar.

\n\n http://.../crisis-center(popup:compose)\n\n\n

The relevant part of the URL follows the ...:

\n\n

Click the Heroes link and look at the URL again.

\n\n http://.../heroes(popup:compose)\n\n

The primary navigation part has changed; the secondary route is the same.

\n

The router is keeping track of two separate branches in a navigation tree and generating a representation of that tree in the URL.

\n

You can add many more outlets and routes, at the top level and in nested levels, creating a navigation tree with many branches and the router will generate the URLs to go with it.

\n

You can tell the router to navigate an entire tree at once by filling out the outlets object and then pass that object inside a link parameters array to the router.navigate method.

\n\n

Clearing secondary routeslink

\n

Like regular outlets, secondary outlets persists until you navigate away to a new component.

\n

Each secondary outlet has its own navigation, independent of the navigation driving the primary outlet.\nChanging a current route that displays in the primary outlet has no effect on the popup outlet.\nThat's why the popup stays visible as you navigate among the crises and heroes.

\n

The closePopup() method again:

\n\nclosePopup() {\n // Providing a `null` value to the named outlet\n // clears the contents of the named outlet\n this.router.navigate([{ outlets: { popup: null }}]);\n}\n\n\n

Clicking the \"send\" or \"cancel\" buttons clears the popup view.\nThe closePopup() function navigates imperatively with the Router.navigate() method, passing in a link parameters array.

\n

Like the array bound to the Contact RouterLink in the AppComponent, this one includes an object with an outlets property.\nThe outlets property value is another object with outlet names for keys.\nThe only named outlet is 'popup'.

\n

This time, the value of 'popup' is null.\nThat's not a route, but it is a legitimate value.\nSetting the popup RouterOutlet to null clears the outlet and removes the secondary popup route from the current URL.

\n\n\n

Milestone 5: Route guardslink

\n

At the moment, any user can navigate anywhere in the application anytime, but sometimes you need to control access to different parts of your app for various reasons. Some of which may include the following:

\n\n

You add guards to the route configuration to handle these scenarios.

\n

A guard's return value controls the router's behavior:

\n\n
\n

Note: The guard can also tell the router to navigate elsewhere, effectively canceling the current navigation.\nWhen doing so inside a guard, the guard should return false;

\n
\n

The guard might return its boolean answer synchronously.\nBut in many cases, the guard can't produce an answer synchronously.\nThe guard could ask the user a question, save changes to the server, or fetch fresh data.\nThese are all asynchronous operations.

\n

Accordingly, a routing guard can return an Observable<boolean> or a Promise<boolean> and the\nrouter will wait for the observable to resolve to true or false.

\n
\n

Note: The observable provided to the Router must also complete. If the observable does not complete, the navigation does not continue.

\n
\n

The router supports multiple guard interfaces:

\n\n

You can have multiple guards at every level of a routing hierarchy.\nThe router checks the CanDeactivate and CanActivateChild guards first, from the deepest child route to the top.\nThen it checks the CanActivate guards from the top down to the deepest child route.\nIf the feature module is loaded asynchronously, the CanLoad guard is checked before the module is loaded.\nIf any guard returns false, pending guards that have not completed will be canceled, and the entire navigation is canceled.

\n

There are several examples over the next few sections.

\n\n

CanActivate: requiring authenticationlink

\n

Applications often restrict access to a feature area based on who the user is.\nYou could permit access only to authenticated users or to users with a specific role.\nYou might block or limit access until the user's account is activated.

\n

The CanActivate guard is the tool to manage these navigation business rules.

\n

Add an admin feature modulelink

\n

This section guides you through extending the crisis center with some new administrative features.\nStart by adding a new feature module named AdminModule.

\n

Generate an admin folder with a feature module file and a routing configuration file.

\n\n ng generate module admin --routing\n\n

Next, generate the supporting components.

\n\n ng generate component admin/admin-dashboard\n\n\n ng generate component admin/admin\n\n\n ng generate component admin/manage-crises\n\n\n ng generate component admin/manage-heroes\n\n

The admin feature file structure looks like this:

\n
\n
\n src/app/admin\n
\n
\n
\n admin\n
\n
\n
\n admin.component.css\n
\n
\n admin.component.html\n
\n
\n admin.component.ts\n
\n
\n
\n admin-dashboard\n
\n
\n
\n admin-dashboard.component.css\n
\n
\n admin-dashboard.component.html\n
\n
\n admin-dashboard.component.ts\n
\n
\n
\n manage-crises\n
\n
\n
\n manage-crises.component.css\n
\n
\n manage-crises.component.html\n
\n
\n manage-crises.component.ts\n
\n
\n
\n manage-heroes\n
\n
\n
\n manage-heroes.component.css\n
\n
\n manage-heroes.component.html\n
\n
\n manage-heroes.component.ts\n
\n
\n
\n admin.module.ts\n
\n
\n admin-routing.module.ts\n
\n
\n
\n

The admin feature module contains the AdminComponent used for routing within the\nfeature module, a dashboard route and two unfinished components to manage crises and heroes.

\n\n\n \n<h3>ADMIN</h3>\n<nav>\n <a routerLink=\"./\" routerLinkActive=\"active\"\n [routerLinkActiveOptions]=\"{ exact: true }\">Dashboard</a>\n <a routerLink=\"./crises\" routerLinkActive=\"active\">Manage Crises</a>\n <a routerLink=\"./heroes\" routerLinkActive=\"active\">Manage Heroes</a>\n</nav>\n<router-outlet></router-outlet>\n\n\n\n \n<p>Dashboard</p>\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\n\nimport { AdminComponent } from './admin/admin.component';\nimport { AdminDashboardComponent } from './admin-dashboard/admin-dashboard.component';\nimport { ManageCrisesComponent } from './manage-crises/manage-crises.component';\nimport { ManageHeroesComponent } from './manage-heroes/manage-heroes.component';\n\nimport { AdminRoutingModule } from './admin-routing.module';\n\n@NgModule({\n imports: [\n CommonModule,\n AdminRoutingModule\n ],\n declarations: [\n AdminComponent,\n AdminDashboardComponent,\n ManageCrisesComponent,\n ManageHeroesComponent\n ]\n})\nexport class AdminModule {}\n\n\n\n\n \n<p>Manage your crises here</p>\n\n\n\n \n<p>Manage your heroes here</p>\n\n\n\n\n
\n

Although the admin dashboard RouterLink only contains a relative slash without an additional URL segment, it is a match to any route within the admin feature area.\nYou only want the Dashboard link to be active when the user visits that route.\nAdding an additional binding to the Dashboard routerLink,[routerLinkActiveOptions]=\"{ exact: true }\", marks the ./ link as active when the user navigates to the /admin URL and not when navigating to any of the child routes.

\n
\n\n
Component-less route: grouping routes without a componentlink
\n

The initial admin routing configuration:

\n\nconst adminRoutes: Routes = [\n {\n path: 'admin',\n component: AdminComponent,\n children: [\n {\n path: '',\n children: [\n { path: 'crises', component: ManageCrisesComponent },\n { path: 'heroes', component: ManageHeroesComponent },\n { path: '', component: AdminDashboardComponent }\n ]\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(adminRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AdminRoutingModule {}\n\n\n

The child route under the AdminComponent has a path and a children property but it's not using a component.\nThis defines a component-less route.

\n

To group the Crisis Center management routes under the admin path a component is unnecessary.\nAdditionally, a component-less route makes it easier to guard child routes.

\n

Next, import the AdminModule into app.module.ts and add it to the imports array\nto register the admin routes.

\n\nimport { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule } from '@angular/forms';\n\nimport { AppComponent } from './app.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\nimport { ComposeMessageComponent } from './compose-message/compose-message.component';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { HeroesModule } from './heroes/heroes.module';\nimport { CrisisCenterModule } from './crisis-center/crisis-center.module';\n\nimport { AdminModule } from './admin/admin.module';\n\n@NgModule({\n imports: [\n CommonModule,\n FormsModule,\n HeroesModule,\n CrisisCenterModule,\n AdminModule,\n AppRoutingModule\n ],\n declarations: [\n AppComponent,\n ComposeMessageComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n

Add an \"Admin\" link to the AppComponent shell so that users can get to this feature.

\n\n<h1 class=\"title\">Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/heroes\" routerLinkActive=\"active\">Heroes</a>\n <a routerLink=\"/admin\" routerLinkActive=\"active\">Admin</a>\n <a [routerLink]=\"[{ outlets: { popup: ['compose'] } }]\">Contact</a>\n</nav>\n<div [@routeAnimation]=\"getAnimationData(routerOutlet)\">\n <router-outlet #routerOutlet=\"outlet\"></router-outlet>\n</div>\n<router-outlet name=\"popup\"></router-outlet>\n\n\n\n

Guard the admin featurelink

\n

Currently, every route within the Crisis Center is open to everyone.\nThe new admin feature should be accessible only to authenticated users.

\n

Write a canActivate() guard method to redirect anonymous users to the\nlogin page when they try to enter the admin area.

\n

Generate an AuthGuard in the auth folder.

\n\n ng generate guard auth/auth\n\n

To demonstrate the fundamentals, this example only logs to the console, returns true immediately, and allows navigation to proceed:

\n\nimport { Injectable } from '@angular/core';\nimport { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthGuard implements CanActivate {\n canActivate(\n next: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): boolean {\n console.log('AuthGuard#canActivate called');\n return true;\n }\n}\n\n\n\n

Next, open admin-routing.module.ts, import the AuthGuard class, and\nupdate the admin route with a canActivate guard property that references it:

\n\nimport { AuthGuard } from '../auth/auth.guard';\n\nconst adminRoutes: Routes = [\n {\n path: 'admin',\n component: AdminComponent,\n canActivate: [AuthGuard],\n children: [\n {\n path: '',\n children: [\n { path: 'crises', component: ManageCrisesComponent },\n { path: 'heroes', component: ManageHeroesComponent },\n { path: '', component: AdminDashboardComponent }\n ],\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(adminRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AdminRoutingModule {}\n\n\n

The admin feature is now protected by the guard, but the guard requires more customization to work fully.

\n\n

Authenticate with AuthGuardlink

\n

Make the AuthGuard mimic authentication.

\n

The AuthGuard should call an application service that can login a user and retain information about the current user. Generate a new AuthService in the auth folder:

\n\n ng generate service auth/auth\n\n

Update the AuthService to log in the user:

\n\nimport { Injectable } from '@angular/core';\n\nimport { Observable, of } from 'rxjs';\nimport { tap, delay } from 'rxjs/operators';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthService {\n isLoggedIn = false;\n\n // store the URL so we can redirect after logging in\n redirectUrl: string;\n\n login(): Observable<boolean> {\n return of(true).pipe(\n delay(1000),\n tap(val => this.isLoggedIn = true)\n );\n }\n\n logout(): void {\n this.isLoggedIn = false;\n }\n}\n\n\n\n

Although it doesn't actually log in, it has an isLoggedIn flag to tell you whether the user is authenticated.\nIts login() method simulates an API call to an external service by returning an observable that resolves successfully after a short pause.\nThe redirectUrl property stores the URL that the user wanted to access so you can navigate to it after authentication.

\n
\n

To keep things minimal, this example redirects unauthenticated users to /admin.

\n
\n

Revise the AuthGuard to call the AuthService.

\n\nimport { Injectable } from '@angular/core';\nimport { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';\n\nimport { AuthService } from './auth.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthGuard implements CanActivate {\n constructor(private authService: AuthService, private router: Router) {}\n\n canActivate(\n next: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): true|UrlTree {\n const url: string = state.url;\n\n return this.checkLogin(url);\n }\n\n checkLogin(url: string): true|UrlTree {\n if (this.authService.isLoggedIn) { return true; }\n\n // Store the attempted URL for redirecting\n this.authService.redirectUrl = url;\n\n // Redirect to the login page\n return this.router.parseUrl('/login');\n }\n}\n\n\n

Notice that you inject the AuthService and the Router in the constructor.\nYou haven't provided the AuthService yet but it's good to know that you can inject helpful services into routing guards.

\n

This guard returns a synchronous boolean result.\nIf the user is logged in, it returns true and the navigation continues.

\n

The ActivatedRouteSnapshot contains the future route that will be activated and the RouterStateSnapshot contains the future RouterState of the application, should you pass through the guard check.

\n

If the user is not logged in, you store the attempted URL the user came from using the RouterStateSnapshot.url and tell the router to redirect to a login page—a page you haven't created yet.\nReturning a UrlTree tells the Router to cancel the current navigation and schedule a new one to redirect the user.

\n\n

Add the LoginComponentlink

\n

You need a LoginComponent for the user to log in to the app. After logging in, you'll redirect to the stored URL if available, or use the default URL.\nThere is nothing new about this component or the way you use it in the router configuration.

\n\n ng generate component auth/login\n\n

Register a /login route in the auth/auth-routing.module.ts.\nIn app.module.ts, import and add the AuthModule to the AppModule imports.

\n\n\n \nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n\nimport { AppComponent } from './app.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\nimport { ComposeMessageComponent } from './compose-message/compose-message.component';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { HeroesModule } from './heroes/heroes.module';\nimport { AuthModule } from './auth/auth.module';\n\n@NgModule({\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n FormsModule,\n HeroesModule,\n AuthModule,\n AppRoutingModule,\n ],\n declarations: [\n AppComponent,\n ComposeMessageComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule {\n}\n\n\n\n \n<h2>LOGIN</h2>\n<p>{{message}}</p>\n<p>\n <button (click)=\"login()\" *ngIf=\"!authService.isLoggedIn\">Login</button>\n <button (click)=\"logout()\" *ngIf=\"authService.isLoggedIn\">Logout</button>\n</p>\n\n\n\n \nimport { Component } from '@angular/core';\nimport { Router } from '@angular/router';\nimport { AuthService } from '../auth.service';\n\n@Component({\n selector: 'app-login',\n templateUrl: './login.component.html',\n styleUrls: ['./login.component.css']\n})\nexport class LoginComponent {\n message: string;\n\n constructor(public authService: AuthService, public router: Router) {\n this.setMessage();\n }\n\n setMessage() {\n this.message = 'Logged ' + (this.authService.isLoggedIn ? 'in' : 'out');\n }\n\n login() {\n this.message = 'Trying to log in ...';\n\n this.authService.login().subscribe(() => {\n this.setMessage();\n if (this.authService.isLoggedIn) {\n // Usually you would use the redirect URL from the auth service.\n // However to keep the example simple, we will always redirect to `/admin`.\n const redirectUrl = '/admin';\n\n // Redirect the user\n this.router.navigate([redirectUrl]);\n }\n });\n }\n\n logout() {\n this.authService.logout();\n this.setMessage();\n }\n}\n\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule } from '@angular/forms';\n\nimport { LoginComponent } from './login/login.component';\nimport { AuthRoutingModule } from './auth-routing.module';\n\n@NgModule({\n imports: [\n CommonModule,\n FormsModule,\n AuthRoutingModule\n ],\n declarations: [\n LoginComponent\n ]\n})\nexport class AuthModule {}\n\n\n\n\n\n\n

CanActivateChild: guarding child routeslink

\n

You can also protect child routes with the CanActivateChild guard.\nThe CanActivateChild guard is similar to the CanActivate guard.\nThe key difference is that it runs before any child route is activated.

\n

You protected the admin feature module from unauthorized access.\nYou should also protect child routes within the feature module.

\n

Extend the AuthGuard to protect when navigating between the admin routes.\nOpen auth.guard.ts and add the CanActivateChild interface to the imported tokens from the router package.

\n

Next, implement the canActivateChild() method which takes the same arguments as the canActivate() method: an ActivatedRouteSnapshot and RouterStateSnapshot.\nThe canActivateChild() method can return an Observable<boolean|UrlTree> or Promise<boolean|UrlTree> for async checks and a boolean or UrlTree for sync checks.\nThis one returns either true to allow the user to access the admin feature module or UrlTree to redirect the user to the login page instead:

\n\nimport { Injectable } from '@angular/core';\nimport {\n CanActivate, Router,\n ActivatedRouteSnapshot,\n RouterStateSnapshot,\n CanActivateChild,\n UrlTree\n} from '@angular/router';\nimport { AuthService } from './auth.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthGuard implements CanActivate, CanActivateChild {\n constructor(private authService: AuthService, private router: Router) {}\n\n canActivate(\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): true|UrlTree {\n const url: string = state.url;\n\n return this.checkLogin(url);\n }\n\n canActivateChild(\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): true|UrlTree {\n return this.canActivate(route, state);\n }\n\n/* . . . */\n}\n\n\n

Add the same AuthGuard to the component-less admin route to protect all other child routes at one time\ninstead of adding the AuthGuard to each route individually.

\n\nconst adminRoutes: Routes = [\n {\n path: 'admin',\n component: AdminComponent,\n canActivate: [AuthGuard],\n children: [\n {\n path: '',\n canActivateChild: [AuthGuard],\n children: [\n { path: 'crises', component: ManageCrisesComponent },\n { path: 'heroes', component: ManageHeroesComponent },\n { path: '', component: AdminDashboardComponent }\n ]\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(adminRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AdminRoutingModule {}\n\n\n\n

CanDeactivate: handling unsaved changeslink

\n

Back in the \"Heroes\" workflow, the app accepts every change to a hero immediately without validation.

\n

In the real world, you might have to accumulate the users changes, validate across fields, validate on the server, or hold changes in a pending state until the user confirms them as a group or cancels and reverts all changes.

\n

When the user navigates away, you can let the user decide what to do with unsaved changes.\nIf the user cancels, you'll stay put and allow more changes.\nIf the user approves, the app can save.

\n

You still might delay navigation until the save succeeds.\nIf you let the user move to the next screen immediately and saving were to fail (perhaps the data is ruled invalid), you would lose the context of the error.

\n

You need to stop the navigation while you wait, asynchronously, for the server to return with its answer.

\n

The CanDeactivate guard helps you decide what to do with unsaved changes and how to proceed.

\n\n

Cancel and savelink

\n

Users update crisis information in the CrisisDetailComponent.\nUnlike the HeroDetailComponent, the user changes do not update the crisis entity immediately.\nInstead, the app updates the entity when the user presses the Save button and discards the changes when the user presses the Cancel button.

\n

Both buttons navigate back to the crisis list after save or cancel.

\n\ncancel() {\n this.gotoCrises();\n}\n\nsave() {\n this.crisis.name = this.editName;\n this.gotoCrises();\n}\n\n\n

In this scenario, the user could click the heroes link, cancel, push the browser back button, or navigate away without saving.

\n

This example app asks the user to be explicit with a confirmation dialog box that waits asynchronously for the user's\nresponse.

\n
\n

You could wait for the user's answer with synchronous, blocking code, however, the app is more responsive—and can do other work—by waiting for the user's answer asynchronously.

\n
\n

Generate a Dialog service to handle user confirmation.

\n\n ng generate service dialog\n\n

Add a confirm() method to the DialogService to prompt the user to confirm their intent.\nThe window.confirm is a blocking action that displays a modal dialog and waits for user interaction.

\n\nimport { Injectable } from '@angular/core';\nimport { Observable, of } from 'rxjs';\n\n/**\n * Async modal dialog service\n * DialogService makes this app easier to test by faking this service.\n * TODO: better modal implementation that doesn't use window.confirm\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class DialogService {\n /**\n * Ask user to confirm an action. `message` explains the action and choices.\n * Returns observable resolving to `true`=confirm or `false`=cancel\n */\n confirm(message?: string): Observable<boolean> {\n const confirmation = window.confirm(message || 'Is it OK?');\n\n return of(confirmation);\n }\n}\n\n\n\n

It returns an Observable that resolves when the user eventually decides what to do: either to discard changes and navigate away (true) or to preserve the pending changes and stay in the crisis editor (false).

\n\n

Generate a guard that checks for the presence of a canDeactivate() method in a component—any component.

\n\n ng generate guard can-deactivate\n\n

Paste the following code into your guard.

\n\nimport { Injectable } from '@angular/core';\nimport { CanDeactivate } from '@angular/router';\nimport { Observable } from 'rxjs';\n\nexport interface CanComponentDeactivate {\n canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {\n canDeactivate(component: CanComponentDeactivate) {\n return component.canDeactivate ? component.canDeactivate() : true;\n }\n}\n\n\n\n

While the guard doesn't have to know which component has a deactivate method, it can detect that the CrisisDetailComponent component has the canDeactivate() method and call it.\nThe guard not knowing the details of any component's deactivation method makes the guard reusable.

\n

Alternatively, you could make a component-specific CanDeactivate guard for the CrisisDetailComponent.\nThe canDeactivate() method provides you with the current instance of the component, the current ActivatedRoute, and RouterStateSnapshot in case you needed to access some external information.\nThis would be useful if you only wanted to use this guard for this component and needed to get the component's properties or confirm whether the router should allow navigation away from it.

\n\nimport { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { CanDeactivate,\n ActivatedRouteSnapshot,\n RouterStateSnapshot } from '@angular/router';\n\nimport { CrisisDetailComponent } from './crisis-center/crisis-detail/crisis-detail.component';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class CanDeactivateGuard implements CanDeactivate<CrisisDetailComponent> {\n\n canDeactivate(\n component: CrisisDetailComponent,\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot\n ): Observable<boolean> | boolean {\n // Get the Crisis Center ID\n console.log(route.paramMap.get('id'));\n\n // Get the current URL\n console.log(state.url);\n\n // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged\n if (!component.crisis || component.crisis.name === component.editName) {\n return true;\n }\n // Otherwise ask the user with the dialog service and return its\n // observable which resolves to true or false when the user decides\n return component.dialogService.confirm('Discard changes?');\n }\n}\n\n\n\n

Looking back at the CrisisDetailComponent, it implements the confirmation workflow for unsaved changes.

\n\ncanDeactivate(): Observable<boolean> | boolean {\n // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged\n if (!this.crisis || this.crisis.name === this.editName) {\n return true;\n }\n // Otherwise ask the user with the dialog service and return its\n // observable which resolves to true or false when the user decides\n return this.dialogService.confirm('Discard changes?');\n}\n\n\n

Notice that the canDeactivate() method can return synchronously; it returns true immediately if there is no crisis or there are no pending changes.\nBut it can also return a Promise or an Observable and the router will wait for that to resolve to truthy (navigate) or falsy (stay on the current route).

\n

Add the Guard to the crisis detail route in crisis-center-routing.module.ts using the canDeactivate array property.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { CrisisCenterComponent } from './crisis-center/crisis-center.component';\nimport { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';\n\nimport { CanDeactivateGuard } from '../can-deactivate.guard';\n\nconst crisisCenterRoutes: Routes = [\n {\n path: 'crisis-center',\n component: CrisisCenterComponent,\n children: [\n {\n path: '',\n component: CrisisListComponent,\n children: [\n {\n path: ':id',\n component: CrisisDetailComponent,\n canDeactivate: [CanDeactivateGuard]\n },\n {\n path: '',\n component: CrisisCenterHomeComponent\n }\n ]\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(crisisCenterRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class CrisisCenterRoutingModule { }\n\n\n\n

Now you have given the user a safeguard against unsaved changes.

\n\n\n

Resolve: pre-fetching component datalink

\n

In the Hero Detail and Crisis Detail, the app waited until the route was activated to fetch the respective hero or crisis.

\n

If you were using a real world API, there might be some delay before the data to display is returned from the server.\nYou don't want to display a blank component while waiting for the data.

\n

To improve this behavior, you can pre-fetch data from the server using a resolver so it's ready the\nmoment the route is activated.\nThis also allows you to handle errors before routing to the component.\nThere's no point in navigating to a crisis detail for an id that doesn't have a record.\nIt'd be better to send the user back to the Crisis List that shows only valid crisis centers.

\n

In summary, you want to delay rendering the routed component until all necessary data has been fetched.

\n\n

Fetch data before navigatinglink

\n

At the moment, the CrisisDetailComponent retrieves the selected crisis.\nIf the crisis is not found, the router navigates back to the crisis list view.

\n

The experience might be better if all of this were handled first, before the route is activated.\nA CrisisDetailResolver service could retrieve a Crisis or navigate away, if the Crisis did not exist, before activating the route and creating the CrisisDetailComponent.

\n

Generate a CrisisDetailResolver service file within the Crisis Center feature area.

\n\n ng generate service crisis-center/crisis-detail-resolver\n\n\nimport { Injectable } from '@angular/core';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class CrisisDetailResolverService {\n\n constructor() { }\n\n}\n\n\n\n

Move the relevant parts of the crisis retrieval logic in CrisisDetailComponent.ngOnInit() into the CrisisDetailResolverService.\nImport the Crisis model, CrisisService, and the Router so you can navigate elsewhere if you can't fetch the crisis.

\n

Be explicit and implement the Resolve interface with a type of Crisis.

\n

Inject the CrisisService and Router and implement the resolve() method.\nThat method could return a Promise, an Observable, or a synchronous return value.

\n

The CrisisService.getCrisis() method returns an observable in order to prevent the route from loading until the data is fetched.\nThe Router guards require an observable to complete, which means it has emitted all\nof its values.\nYou use the take operator with an argument of 1 to ensure that the Observable completes after retrieving the first value from the Observable returned by the getCrisis() method.

\n

If it doesn't return a valid Crisis, then return an empty Observable, cancel the previous in-progress navigation to the CrisisDetailComponent, and navigate the user back to the CrisisListComponent.\nThe updated resolver service looks like this:

\n\nimport { Injectable } from '@angular/core';\nimport {\n Router, Resolve,\n RouterStateSnapshot,\n ActivatedRouteSnapshot\n} from '@angular/router';\nimport { Observable, of, EMPTY } from 'rxjs';\nimport { mergeMap, take } from 'rxjs/operators';\n\nimport { CrisisService } from './crisis.service';\nimport { Crisis } from './crisis';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class CrisisDetailResolverService implements Resolve<Crisis> {\n constructor(private cs: CrisisService, private router: Router) {}\n\n resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Crisis> | Observable<never> {\n const id = route.paramMap.get('id');\n\n return this.cs.getCrisis(id).pipe(\n take(1),\n mergeMap(crisis => {\n if (crisis) {\n return of(crisis);\n } else { // id not found\n this.router.navigate(['/crisis-center']);\n return EMPTY;\n }\n })\n );\n }\n}\n\n\n\n

Import this resolver in the crisis-center-routing.module.ts and add a resolve object to the CrisisDetailComponent route configuration.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { CrisisCenterComponent } from './crisis-center/crisis-center.component';\nimport { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';\n\nimport { CanDeactivateGuard } from '../can-deactivate.guard';\nimport { CrisisDetailResolverService } from './crisis-detail-resolver.service';\n\nconst crisisCenterRoutes: Routes = [\n {\n path: 'crisis-center',\n component: CrisisCenterComponent,\n children: [\n {\n path: '',\n component: CrisisListComponent,\n children: [\n {\n path: ':id',\n component: CrisisDetailComponent,\n canDeactivate: [CanDeactivateGuard],\n resolve: {\n crisis: CrisisDetailResolverService\n }\n },\n {\n path: '',\n component: CrisisCenterHomeComponent\n }\n ]\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(crisisCenterRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class CrisisCenterRoutingModule { }\n\n\n

The CrisisDetailComponent should no longer fetch the crisis.\nWhen you re-configured the route, you changed where the crisis is.\nUpdate the CrisisDetailComponent to get the crisis from the ActivatedRoute.data.crisis property instead;

\n\nngOnInit() {\n this.route.data\n .subscribe((data: { crisis: Crisis }) => {\n this.editName = data.crisis.name;\n this.crisis = data.crisis;\n });\n}\n\n\n

Note the following three important points:

\n
    \n
  1. \n

    The router's Resolve interface is optional.\nThe CrisisDetailResolverService doesn't inherit from a base class.\nThe router looks for that method and calls it if found.

    \n
  2. \n
  3. \n

    The router calls the resolver in any case where the user could navigate away so you don't have to code for each use case.

    \n
  4. \n
  5. \n

    Returning an empty Observable in at least one resolver will cancel navigation.

    \n
  6. \n
\n

The relevant Crisis Center code for this milestone follows.

\n\n\n \n<h1 class=\"title\">Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/superheroes\" routerLinkActive=\"active\">Heroes</a>\n <a routerLink=\"/admin\" routerLinkActive=\"active\">Admin</a>\n <a routerLink=\"/login\" routerLinkActive=\"active\">Login</a>\n <a [routerLink]=\"[{ outlets: { popup: ['compose'] } }]\">Contact</a>\n</nav>\n<div [@routeAnimation]=\"getAnimationData(routerOutlet)\">\n <router-outlet #routerOutlet=\"outlet\"></router-outlet>\n</div>\n<router-outlet name=\"popup\"></router-outlet>\n\n\n\n \n<p>Welcome to the Crisis Center</p>\n\n\n\n \n<h2>CRISIS CENTER</h2>\n<router-outlet></router-outlet>\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { CrisisCenterComponent } from './crisis-center/crisis-center.component';\nimport { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';\n\nimport { CanDeactivateGuard } from '../can-deactivate.guard';\nimport { CrisisDetailResolverService } from './crisis-detail-resolver.service';\n\nconst crisisCenterRoutes: Routes = [\n {\n path: 'crisis-center',\n component: CrisisCenterComponent,\n children: [\n {\n path: '',\n component: CrisisListComponent,\n children: [\n {\n path: ':id',\n component: CrisisDetailComponent,\n canDeactivate: [CanDeactivateGuard],\n resolve: {\n crisis: CrisisDetailResolverService\n }\n },\n {\n path: '',\n component: CrisisCenterHomeComponent\n }\n ]\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(crisisCenterRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class CrisisCenterRoutingModule { }\n\n\n\n \n<ul class=\"crises\">\n <li *ngFor=\"let crisis of crises$ | async\"\n [class.selected]=\"crisis.id === selectedId\">\n <a [routerLink]=\"[crisis.id]\">\n <span class=\"badge\">{{ crisis.id }}</span>{{ crisis.name }}\n </a>\n </li>\n</ul>\n\n<router-outlet></router-outlet>\n\n\n\n\n \nimport { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\n\nimport { CrisisService } from '../crisis.service';\nimport { Crisis } from '../crisis';\nimport { Observable } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\n\n@Component({\n selector: 'app-crisis-list',\n templateUrl: './crisis-list.component.html',\n styleUrls: ['./crisis-list.component.css']\n})\nexport class CrisisListComponent implements OnInit {\n crises$: Observable<Crisis[]>;\n selectedId: number;\n\n constructor(\n private service: CrisisService,\n private route: ActivatedRoute\n ) {}\n\n ngOnInit() {\n this.crises$ = this.route.paramMap.pipe(\n switchMap(params => {\n this.selectedId = +params.get('id');\n return this.service.getCrises();\n })\n );\n }\n}\n\n\n\n\n \n<div *ngIf=\"crisis\">\n <h3>\"{{ editName }}\"</h3>\n <div>\n <label>Id: </label>{{ crisis.id }}</div>\n <div>\n <label>Name: </label>\n <input [(ngModel)]=\"editName\" placeholder=\"name\"/>\n </div>\n <p>\n <button (click)=\"save()\">Save</button>\n <button (click)=\"cancel()\">Cancel</button>\n </p>\n</div>\n\n\n\n \nimport { Component, OnInit, HostBinding } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable } from 'rxjs';\n\nimport { Crisis } from '../crisis';\nimport { DialogService } from '../../dialog.service';\n\n@Component({\n selector: 'app-crisis-detail',\n templateUrl: './crisis-detail.component.html',\n styleUrls: ['./crisis-detail.component.css']\n})\nexport class CrisisDetailComponent implements OnInit {\n crisis: Crisis;\n editName: string;\n\n constructor(\n private route: ActivatedRoute,\n private router: Router,\n public dialogService: DialogService\n ) {}\n\n ngOnInit() {\n this.route.data\n .subscribe((data: { crisis: Crisis }) => {\n this.editName = data.crisis.name;\n this.crisis = data.crisis;\n });\n }\n\n cancel() {\n this.gotoCrises();\n }\n\n save() {\n this.crisis.name = this.editName;\n this.gotoCrises();\n }\n\n canDeactivate(): Observable<boolean> | boolean {\n // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged\n if (!this.crisis || this.crisis.name === this.editName) {\n return true;\n }\n // Otherwise ask the user with the dialog service and return its\n // observable which resolves to true or false when the user decides\n return this.dialogService.confirm('Discard changes?');\n }\n\n gotoCrises() {\n const crisisId = this.crisis ? this.crisis.id : null;\n // Pass along the crisis id if available\n // so that the CrisisListComponent can select that crisis.\n // Add a totally useless `foo` parameter for kicks.\n // Relative navigation back to the crises\n this.router.navigate(['../', { id: crisisId, foo: 'foo' }], { relativeTo: this.route });\n }\n}\n\n\n\n\n \nimport { Injectable } from '@angular/core';\nimport {\n Router, Resolve,\n RouterStateSnapshot,\n ActivatedRouteSnapshot\n} from '@angular/router';\nimport { Observable, of, EMPTY } from 'rxjs';\nimport { mergeMap, take } from 'rxjs/operators';\n\nimport { CrisisService } from './crisis.service';\nimport { Crisis } from './crisis';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class CrisisDetailResolverService implements Resolve<Crisis> {\n constructor(private cs: CrisisService, private router: Router) {}\n\n resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Crisis> | Observable<never> {\n const id = route.paramMap.get('id');\n\n return this.cs.getCrisis(id).pipe(\n take(1),\n mergeMap(crisis => {\n if (crisis) {\n return of(crisis);\n } else { // id not found\n this.router.navigate(['/crisis-center']);\n return EMPTY;\n }\n })\n );\n }\n}\n\n\n\n\n \nimport { BehaviorSubject } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nimport { Injectable } from '@angular/core';\nimport { MessageService } from '../message.service';\nimport { Crisis } from './crisis';\nimport { CRISES } from './mock-crises';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class CrisisService {\n static nextCrisisId = 100;\n private crises$: BehaviorSubject<Crisis[]> = new BehaviorSubject<Crisis[]>(CRISES);\n\n constructor(private messageService: MessageService) { }\n\n getCrises() { return this.crises$; }\n\n getCrisis(id: number | string) {\n return this.getCrises().pipe(\n map(crises => crises.find(crisis => crisis.id === +id))\n );\n }\n\n}\n\n\n\n\n \nimport { Injectable } from '@angular/core';\nimport { Observable, of } from 'rxjs';\n\n/**\n * Async modal dialog service\n * DialogService makes this app easier to test by faking this service.\n * TODO: better modal implementation that doesn't use window.confirm\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class DialogService {\n /**\n * Ask user to confirm an action. `message` explains the action and choices.\n * Returns observable resolving to `true`=confirm or `false`=cancel\n */\n confirm(message?: string): Observable<boolean> {\n const confirmation = window.confirm(message || 'Is it OK?');\n\n return of(confirmation);\n }\n}\n\n\n\n\n\n

Guards

\n\n\n \nimport { Injectable } from '@angular/core';\nimport {\n CanActivate, Router,\n ActivatedRouteSnapshot,\n RouterStateSnapshot,\n CanActivateChild,\n UrlTree\n} from '@angular/router';\nimport { AuthService } from './auth.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthGuard implements CanActivate, CanActivateChild {\n constructor(private authService: AuthService, private router: Router) {}\n\n canActivate(\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): true|UrlTree {\n const url: string = state.url;\n\n return this.checkLogin(url);\n }\n\n canActivateChild(\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): true|UrlTree {\n return this.canActivate(route, state);\n }\n\n checkLogin(url: string): true|UrlTree {\n if (this.authService.isLoggedIn) { return true; }\n\n // Store the attempted URL for redirecting\n this.authService.redirectUrl = url;\n\n // Redirect to the login page\n return this.router.parseUrl('/login');\n }\n}\n\n\n\n\n \nimport { Injectable } from '@angular/core';\nimport { CanDeactivate } from '@angular/router';\nimport { Observable } from 'rxjs';\n\nexport interface CanComponentDeactivate {\n canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;\n}\n\n@Injectable({\n providedIn: 'root',\n})\nexport class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {\n canDeactivate(component: CanComponentDeactivate) {\n return component.canDeactivate ? component.canDeactivate() : true;\n }\n}\n\n\n\n\n\n\n\n

Query parameters and fragmentslink

\n

In the route parameters section, you only dealt with parameters specific to the route.\nHowever, you can use query parameters to get optional parameters available to all routes.

\n

Fragments refer to certain elements on the page\nidentified with an id attribute.

\n

Update the AuthGuard to provide a session_id query that will remain after navigating to another route.

\n

Add an anchor element so you can jump to a certain point on the page.

\n

Add the NavigationExtras object to the router.navigate() method that navigates you to the /login route.

\n\nimport { Injectable } from '@angular/core';\nimport {\n CanActivate, Router,\n ActivatedRouteSnapshot,\n RouterStateSnapshot,\n CanActivateChild,\n NavigationExtras,\n UrlTree\n} from '@angular/router';\nimport { AuthService } from './auth.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AuthGuard implements CanActivate, CanActivateChild {\n constructor(private authService: AuthService, private router: Router) {}\n\n canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): true|UrlTree {\n const url: string = state.url;\n\n return this.checkLogin(url);\n }\n\n canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): true|UrlTree {\n return this.canActivate(route, state);\n }\n\n checkLogin(url: string): true|UrlTree {\n if (this.authService.isLoggedIn) { return true; }\n\n // Store the attempted URL for redirecting\n this.authService.redirectUrl = url;\n\n // Create a dummy session id\n const sessionId = 123456789;\n\n // Set our navigation extras object\n // that contains our global query params and fragment\n const navigationExtras: NavigationExtras = {\n queryParams: { session_id: sessionId },\n fragment: 'anchor'\n };\n\n // Redirect to the login page with extras\n return this.router.createUrlTree(['/login'], navigationExtras);\n }\n}\n\n\n\n

You can also preserve query parameters and fragments across navigations without having to provide them again when navigating.\nIn the LoginComponent, you'll add an object as the second argument in the router.navigateUrl() function and provide the queryParamsHandling and preserveFragment to pass along the current query parameters and fragment to the next route.

\n\n// Set our navigation extras object\n// that passes on our global query params and fragment\nconst navigationExtras: NavigationExtras = {\n queryParamsHandling: 'preserve',\n preserveFragment: true\n};\n\n// Redirect the user\nthis.router.navigate([redirectUrl], navigationExtras);\n\n\n
\n

The queryParamsHandling feature also provides a merge option, which preserves and combines the current query parameters with any provided query parameters when navigating.

\n
\n

To navigate to the Admin Dashboard route after logging in, update admin-dashboard.component.ts to handle the\nquery parameters and fragment.

\n\nimport { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\n@Component({\n selector: 'app-admin-dashboard',\n templateUrl: './admin-dashboard.component.html',\n styleUrls: ['./admin-dashboard.component.css']\n})\nexport class AdminDashboardComponent implements OnInit {\n sessionId: Observable<string>;\n token: Observable<string>;\n\n constructor(private route: ActivatedRoute) {}\n\n ngOnInit() {\n // Capture the session ID if available\n this.sessionId = this.route\n .queryParamMap\n .pipe(map(params => params.get('session_id') || 'None'));\n\n // Capture the fragment if available\n this.token = this.route\n .fragment\n .pipe(map(fragment => fragment || 'None'));\n }\n}\n\n\n\n

Query parameters and fragments are also available through the ActivatedRoute service.\nJust like route parameters, the query parameters and fragments are provided as an Observable.\nThe updated Crisis Admin component feeds the Observable directly into the template using the AsyncPipe.

\n

Now, you can click on the Admin button, which takes you to the Login page with the provided queryParamMap and fragment.\nAfter you click the login button, notice that you have been redirected to the Admin Dashboard page with the query parameters and fragment still intact in the address bar.

\n

You can use these persistent bits of information for things that need to be provided across pages like authentication tokens or session ids.

\n
\n

The query params and fragment can also be preserved using a RouterLink with\nthe queryParamsHandling and preserveFragment bindings respectively.

\n
\n\n

Milestone 6: Asynchronous routinglink

\n

As you've worked through the milestones, the application has naturally gotten larger.\nAt some point you'll reach a point where the application takes a long time to load.

\n

To remedy this issue, use asynchronous routing, which loads feature modules lazily, on request.\nLazy loading has multiple benefits.

\n\n

You're already part of the way there.\nBy organizing the application into modules—AppModule,\nHeroesModule, AdminModule and CrisisCenterModule—you\nhave natural candidates for lazy loading.

\n

Some modules, like AppModule, must be loaded from the start.\nBut others can and should be lazy loaded.\nThe AdminModule, for example, is needed by a few authorized users, so\nyou should only load it when requested by the right people.

\n\n

Lazy Loading route configurationlink

\n

Change the admin path in the admin-routing.module.ts from 'admin' to an empty string, '', the empty path.

\n

Use empty path routes to group routes together without adding any additional path segments to the URL.\nUsers will still visit /admin and the AdminComponent still serves as the Routing Component containing child routes.

\n

Open the AppRoutingModule and add a new admin route to its appRoutes array.

\n

Give it a loadChildren property instead of a children property.\nThe loadChildren property takes a function that returns a promise using the browser's built-in syntax for lazy loading code using dynamic imports import('...').\nThe path is the location of the AdminModule (relative to the app root).\nAfter the code is requested and loaded, the Promise resolves an object that contains the NgModule, in this case the AdminModule.

\n\n{\n path: 'admin',\n loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),\n},\n\n\n
\n

Note: When using absolute paths, the NgModule file location must begin with src/app in order to resolve correctly. For custom path mapping with absolute paths, you must configure the baseUrl and paths properties in the project tsconfig.json.

\n
\n

When the router navigates to this route, it uses the loadChildren string to dynamically load the AdminModule.\nThen it adds the AdminModule routes to its current route configuration.\nFinally, it loads the requested route to the destination admin component.

\n

The lazy loading and re-configuration happen just once, when the route is first requested; the module and routes are available immediately for subsequent requests.

\n
\n

Angular provides a built-in module loader that supports SystemJS to load modules asynchronously. If you were\nusing another bundling tool, such as Webpack, you would use the Webpack mechanism for asynchronously loading modules.

\n
\n

Take the final step and detach the admin feature set from the main application.\nThe root AppModule must neither load nor reference the AdminModule or its files.

\n

In app.module.ts, remove the AdminModule import statement from the top of the file\nand remove the AdminModule from the NgModule's imports array.

\n\n

CanLoad: guarding unauthorized loading of feature moduleslink

\n

You're already protecting the AdminModule with a CanActivate guard that prevents unauthorized users from accessing the admin feature area.\nIt redirects to the login page if the user is not authorized.

\n

But the router is still loading the AdminModule even if the user can't visit any of its components.\nIdeally, you'd only load the AdminModule if the user is logged in.

\n

Add a CanLoad guard that only loads the AdminModule once the user is logged in and attempts to access the admin feature area.

\n

The existing AuthGuard already has the essential logic in its checkLogin() method to support the CanLoad guard.

\n

Open auth.guard.ts.\nImport the CanLoad interface from @angular/router.\nAdd it to the AuthGuard class's implements list.\nThen implement canLoad() as follows:

\n\ncanLoad(route: Route): boolean {\n const url = `/${route.path}`;\n\n return this.checkLogin(url);\n}\n\n\n

The router sets the canLoad() method's route parameter to the intended destination URL.\nThe checkLogin() method redirects to that URL once the user has logged in.

\n

Now import the AuthGuard into the AppRoutingModule and add the AuthGuard to the canLoad\narray property for the admin route.\nThe completed admin route looks like this:

\n\n{\n path: 'admin',\n loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),\n canLoad: [AuthGuard]\n},\n\n\n\n

Preloading: background loading of feature areaslink

\n

In addition to loading modules on-demand, you can load modules asynchronously with preloading.

\n

The AppModule is eagerly loaded when the application starts, meaning that it loads right away.\nNow the AdminModule loads only when the user clicks on a link, which is called lazy loading.

\n

Preloading allows you to load modules in the background so that the data is ready to render when the user activates a particular route.\nConsider the Crisis Center.\nIt isn't the first view that a user sees.\nBy default, the Heroes are the first view.\nFor the smallest initial payload and fastest launch time, you should eagerly load the AppModule and the HeroesModule.

\n

You could lazy load the Crisis Center.\nBut you're almost certain that the user will visit the Crisis Center within minutes of launching the app.\nIdeally, the app would launch with just the AppModule and the HeroesModule loaded and then, almost immediately, load the CrisisCenterModule in the background.\nBy the time the user navigates to the Crisis Center, its module will have been loaded and ready.

\n\n

How preloading workslink

\n

After each successful navigation, the router looks in its configuration for an unloaded module that it can preload.\nWhether it preloads a module, and which modules it preloads, depends upon the preload strategy.

\n

The Router offers two preloading strategies:

\n\n

The router either never preloads, or preloads every lazy loaded module.\nThe Router also supports custom preloading strategies for fine control over which modules to preload and when.

\n

This section guides you through updating the CrisisCenterModule to load lazily by default and use the PreloadAllModules strategy to load all lazy loaded modules.

\n\n

Lazy load the crisis centerlink

\n

Update the route configuration to lazy load the CrisisCenterModule.\nTake the same steps you used to configure AdminModule for lazy loading.

\n
    \n
  1. \n

    Change the crisis-center path in the CrisisCenterRoutingModule to an empty string.

    \n
  2. \n
  3. \n

    Add a crisis-center route to the AppRoutingModule.

    \n
  4. \n
  5. \n

    Set the loadChildren string to load the CrisisCenterModule.

    \n
  6. \n
  7. \n

    Remove all mention of the CrisisCenterModule from app.module.ts.

    \n
  8. \n
\n

Here are the updated modules before enabling preload:

\n\n\n \nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\n\nimport { Router } from '@angular/router';\n\nimport { AppComponent } from './app.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\nimport { ComposeMessageComponent } from './compose-message/compose-message.component';\n\nimport { AppRoutingModule } from './app-routing.module';\nimport { HeroesModule } from './heroes/heroes.module';\nimport { AuthModule } from './auth/auth.module';\n\n@NgModule({\n imports: [\n BrowserModule,\n BrowserAnimationsModule,\n FormsModule,\n HeroesModule,\n AuthModule,\n AppRoutingModule,\n ],\n declarations: [\n AppComponent,\n ComposeMessageComponent,\n PageNotFoundComponent\n ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule {\n}\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport {\n RouterModule, Routes,\n} from '@angular/router';\n\nimport { ComposeMessageComponent } from './compose-message/compose-message.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nimport { AuthGuard } from './auth/auth.guard';\n\nconst appRoutes: Routes = [\n {\n path: 'compose',\n component: ComposeMessageComponent,\n outlet: 'popup'\n },\n {\n path: 'admin',\n loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),\n canLoad: [AuthGuard]\n },\n {\n path: 'crisis-center',\n loadChildren: () => import('./crisis-center/crisis-center.module').then(m => m.CrisisCenterModule)\n },\n { path: '', redirectTo: '/heroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forRoot(\n appRoutes,\n )\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AppRoutingModule {}\n\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { CrisisCenterHomeComponent } from './crisis-center-home/crisis-center-home.component';\nimport { CrisisListComponent } from './crisis-list/crisis-list.component';\nimport { CrisisCenterComponent } from './crisis-center/crisis-center.component';\nimport { CrisisDetailComponent } from './crisis-detail/crisis-detail.component';\n\nimport { CanDeactivateGuard } from '../can-deactivate.guard';\nimport { CrisisDetailResolverService } from './crisis-detail-resolver.service';\n\nconst crisisCenterRoutes: Routes = [\n {\n path: '',\n component: CrisisCenterComponent,\n children: [\n {\n path: '',\n component: CrisisListComponent,\n children: [\n {\n path: ':id',\n component: CrisisDetailComponent,\n canDeactivate: [CanDeactivateGuard],\n resolve: {\n crisis: CrisisDetailResolverService\n }\n },\n {\n path: '',\n component: CrisisCenterHomeComponent\n }\n ]\n }\n ]\n }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(crisisCenterRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class CrisisCenterRoutingModule { }\n\n\n\n\n

You could try this now and confirm that the CrisisCenterModule loads after you click the \"Crisis Center\" button.

\n

To enable preloading of all lazy loaded modules, import the PreloadAllModules token from the Angular router package.

\n

The second argument in the RouterModule.forRoot() method takes an object for additional configuration options.\nThe preloadingStrategy is one of those options.\nAdd the PreloadAllModules token to the forRoot() call:

\n\nRouterModule.forRoot(\n appRoutes,\n {\n enableTracing: true, // <-- debugging purposes only\n preloadingStrategy: PreloadAllModules\n }\n)\n\n\n

This configures the Router preloader to immediately load all lazy loaded routes (routes with a loadChildren property).

\n

When you visit http://localhost:4200, the /heroes route loads immediately upon launch and the router starts loading the CrisisCenterModule right after the HeroesModule loads.

\n

Currently, the AdminModule does not preload because CanLoad is blocking it.

\n\n

CanLoad blocks preloadlink

\n

The PreloadAllModules strategy does not load feature areas protected by a CanLoad guard.

\n

You added a CanLoad guard to the route in the AdminModule a few steps back to block loading of that module until the user is authorized.\nThat CanLoad guard takes precedence over the preload strategy.

\n

If you want to preload a module as well as guard against unauthorized access, remove the canLoad() guard method and rely on the canActivate() guard alone.

\n\n

Custom Preloading Strategylink

\n

Preloading every lazy loaded module works well in many situations.\nHowever, in consideration of things such as low bandwidth and user metrics, you can use a custom preloading strategy for specific feature modules.

\n

This section guides you through adding a custom strategy that only preloads routes whose data.preload flag is set to true.\nRecall that you can add anything to the data property of a route.

\n

Set the data.preload flag in the crisis-center route in the AppRoutingModule.

\n\n{\n path: 'crisis-center',\n loadChildren: () => import('./crisis-center/crisis-center.module').then(m => m.CrisisCenterModule),\n data: { preload: true }\n},\n\n\n

Generate a new SelectivePreloadingStrategy service.

\n\n ng generate service selective-preloading-strategy\n\n

Replace the contents of selective-preloading-strategy.service.ts with the following:

\n\nimport { Injectable } from '@angular/core';\nimport { PreloadingStrategy, Route } from '@angular/router';\nimport { Observable, of } from 'rxjs';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class SelectivePreloadingStrategyService implements PreloadingStrategy {\n preloadedModules: string[] = [];\n\n preload(route: Route, load: () => Observable<any>): Observable<any> {\n if (route.data && route.data.preload) {\n // add the route path to the preloaded module array\n this.preloadedModules.push(route.path);\n\n // log the route path to the console\n console.log('Preloaded: ' + route.path);\n\n return load();\n } else {\n return of(null);\n }\n }\n}\n\n\n\n

SelectivePreloadingStrategyService implements the PreloadingStrategy, which has one method, preload().

\n

The router calls the preload() method with two arguments:

\n
    \n
  1. The route to consider.
  2. \n
  3. A loader function that can load the routed module asynchronously.
  4. \n
\n

An implementation of preload must return an Observable.\nIf the route does preload, it returns the observable returned by calling the loader function.\nIf the route does not preload, it returns an Observable of null.

\n

In this sample, the preload() method loads the route if the route's data.preload flag is truthy.

\n

As a side-effect, SelectivePreloadingStrategyService logs the path of a selected route in its public preloadedModules array.

\n

Shortly, you'll extend the AdminDashboardComponent to inject this service and display its preloadedModules array.

\n

But first, make a few changes to the AppRoutingModule.

\n
    \n
  1. Import SelectivePreloadingStrategyService into AppRoutingModule.
  2. \n
  3. Replace the PreloadAllModules strategy in the call to forRoot() with this SelectivePreloadingStrategyService.
  4. \n
  5. Add the SelectivePreloadingStrategyService strategy to the AppRoutingModule providers array so you can inject it elsewhere in the app.
  6. \n
\n

Now edit the AdminDashboardComponent to display the log of preloaded routes.

\n
    \n
  1. Import the SelectivePreloadingStrategyService.
  2. \n
  3. Inject it into the dashboard's constructor.
  4. \n
  5. Update the template to display the strategy service's preloadedModules array.
  6. \n
\n

Now the file is as follows:

\n\nimport { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nimport { SelectivePreloadingStrategyService } from '../../selective-preloading-strategy.service';\n\n@Component({\n selector: 'app-admin-dashboard',\n templateUrl: './admin-dashboard.component.html',\n styleUrls: ['./admin-dashboard.component.css']\n})\nexport class AdminDashboardComponent implements OnInit {\n sessionId: Observable<string>;\n token: Observable<string>;\n modules: string[];\n\n constructor(\n private route: ActivatedRoute,\n preloadStrategy: SelectivePreloadingStrategyService\n ) {\n this.modules = preloadStrategy.preloadedModules;\n }\n\n ngOnInit() {\n // Capture the session ID if available\n this.sessionId = this.route\n .queryParamMap\n .pipe(map(params => params.get('session_id') || 'None'));\n\n // Capture the fragment if available\n this.token = this.route\n .fragment\n .pipe(map(fragment => fragment || 'None'));\n }\n}\n\n\n\n

Once the application loads the initial route, the CrisisCenterModule is preloaded.\nVerify this by logging in to the Admin feature area and noting that the crisis-center is listed in the Preloaded Modules.\nIt also logs to the browser's console.

\n\n

Migrating URLs with redirectslink

\n

You've setup the routes for navigating around your application and used navigation imperatively and declaratively.\nBut like any application, requirements change over time.\nYou've setup links and navigation to /heroes and /hero/:id from the HeroListComponent and HeroDetailComponent components.\nIf there were a requirement that links to heroes become superheroes, you would still want the previous URLs to navigate correctly.\nYou also don't want to update every link in your application, so redirects makes refactoring routes trivial.

\n\n

Changing /heroes to /superheroeslink

\n

This section guides you through migrating the Hero routes to new URLs.\nThe Router checks for redirects in your configuration before navigating, so each redirect is triggered when needed. To support this change, add redirects from the old routes to the new routes in the heroes-routing.module.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { HeroListComponent } from './hero-list/hero-list.component';\nimport { HeroDetailComponent } from './hero-detail/hero-detail.component';\n\nconst heroesRoutes: Routes = [\n { path: 'heroes', redirectTo: '/superheroes' },\n { path: 'hero/:id', redirectTo: '/superhero/:id' },\n { path: 'superheroes', component: HeroListComponent, data: { animation: 'heroes' } },\n { path: 'superhero/:id', component: HeroDetailComponent, data: { animation: 'hero' } }\n];\n\n@NgModule({\n imports: [\n RouterModule.forChild(heroesRoutes)\n ],\n exports: [\n RouterModule\n ]\n})\nexport class HeroesRoutingModule { }\n\n\n

Notice two different types of redirects.\nThe first change is from /heroes to /superheroes without any parameters.\nThe second change is from /hero/:id to /superhero/:id, which includes the :id route parameter.\nRouter redirects also use powerful pattern-matching, so the Router inspects the URL and replaces route parameters in the path with their appropriate destination.\nPreviously, you navigated to a URL such as /hero/15 with a route parameter id of 15.

\n
\n

The Router also supports query parameters and the fragment when using redirects.

\n\n
\n

Currently, the empty path route redirects to /heroes, which redirects to /superheroes.\nThis won't work because the Router handles redirects once at each level of routing configuration.\nThis prevents chaining of redirects, which can lead to endless redirect loops.

\n

Instead, update the empty path route in app-routing.module.ts to redirect to /superheroes.

\n\nimport { NgModule } from '@angular/core';\nimport { RouterModule, Routes } from '@angular/router';\n\nimport { ComposeMessageComponent } from './compose-message/compose-message.component';\nimport { PageNotFoundComponent } from './page-not-found/page-not-found.component';\n\nimport { AuthGuard } from './auth/auth.guard';\nimport { SelectivePreloadingStrategyService } from './selective-preloading-strategy.service';\n\nconst appRoutes: Routes = [\n {\n path: 'compose',\n component: ComposeMessageComponent,\n outlet: 'popup'\n },\n {\n path: 'admin',\n loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),\n canLoad: [AuthGuard]\n },\n {\n path: 'crisis-center',\n loadChildren: () => import('./crisis-center/crisis-center.module').then(m => m.CrisisCenterModule),\n data: { preload: true }\n },\n { path: '', redirectTo: '/superheroes', pathMatch: 'full' },\n { path: '**', component: PageNotFoundComponent }\n];\n\n@NgModule({\n imports: [\n RouterModule.forRoot(\n appRoutes,\n {\n enableTracing: false, // <-- debugging purposes only\n preloadingStrategy: SelectivePreloadingStrategyService,\n }\n )\n ],\n exports: [\n RouterModule\n ]\n})\nexport class AppRoutingModule { }\n\n\n\n

A routerLink isn't tied to route configuration, so update the associated router links to remain active when the new route is active.\nUpdate the app.component.ts template for the /heroes routerLink.

\n\n<h1 class=\"title\">Angular Router</h1>\n<nav>\n <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\n <a routerLink=\"/superheroes\" routerLinkActive=\"active\">Heroes</a>\n <a routerLink=\"/admin\" routerLinkActive=\"active\">Admin</a>\n <a routerLink=\"/login\" routerLinkActive=\"active\">Login</a>\n <a [routerLink]=\"[{ outlets: { popup: ['compose'] } }]\">Contact</a>\n</nav>\n<div [@routeAnimation]=\"getAnimationData(routerOutlet)\">\n <router-outlet #routerOutlet=\"outlet\"></router-outlet>\n</div>\n<router-outlet name=\"popup\"></router-outlet>\n\n\n

Update the goToHeroes() method in the hero-detail.component.ts to navigate back to /superheroes with the optional route parameters.

\n\ngotoHeroes(hero: Hero) {\n const heroId = hero ? hero.id : null;\n // Pass along the hero id if available\n // so that the HeroList component can select that hero.\n // Include a junk 'foo' property for fun.\n this.router.navigate(['/superheroes', { id: heroId, foo: 'foo' }]);\n}\n\n\n

With the redirects setup, all previous routes now point to their new destinations and both URLs still function as intended.

\n\n

Inspect the router's configurationlink

\n

To determine if your routes are actually evaluated in the proper order, you can inspect the router's configuration.

\n

Do this by injecting the router and logging to the console its config property.\nFor example, update the AppModule as follows and look in the browser console window\nto see the finished route configuration.

\n\nexport class AppModule {\n // Diagnostic only: inspect router configuration\n constructor(router: Router) {\n // Use a custom replacer to display function names in the route configs\n const replacer = (key, value) => (typeof value === 'function') ? value.name : value;\n\n console.log('Routes: ', JSON.stringify(router.config, replacer, 2));\n }\n}\n\n\n\n

Final applink

\n

For the completed router app, see the for the final source code.

\n\n\n \n\n\n\n" }