We received new requirements for our Tour of Heroes application:


When we’re done, users will be able to navigate the app like this:



We'll add Angular’s Router to our app to satisfy these requirements.

我们将把 Angular 路由器加入应用中,以满足这些需求。 (译注:硬件领域中的路由器是用来帮你找到另一台网络设备的,而这里的路由器用于帮你找到一个组件)

The Routing and Navigation chapter covers the router in more detail than we will in this tutorial.


Run the for this part.



To see the URL changes in the browser address bar, pop out the preview window by clicking the blue 'X' button in the upper right corner:

注意看浏览器地址栏中的 URL 变化,点击右上角的蓝色'X'按钮,弹出预览窗口。

Where We Left Off


Before we continue with our Tour of Heroes, let’s verify that we have the following structure after adding our hero service and hero detail component. If not, we’ll need to go back and follow the previous chapters.


node_modules ...

Keep the app transpiling and running


Open a terminal/console window and enter the following command to start the TypeScript compiler, start the server, and watch for changes:

打开终端/控制台窗口,运行下列命令启动 TypeScript 编译器,它会监视文件变更,并启动开发服务器:

npm start

The application runs and updates automatically as we continue to build the Tour of Heroes.


Action plan


Here's our plan:


Routing is another name for navigation. The router is the mechanism for navigating from view to view.


Splitting the AppComponent

拆分 AppComponent

Our current app loads AppComponent and immediately displays the list of heroes.


Our revised app should present a shell with a choice of views (Dashboard and Heroes) and then default to one of them.


The AppComponent should only handle navigation. Let's move the display of Heroes out of AppComponent and into its own HeroesComponent.

AppComponent组件应该只处理导航。 我们来把英雄列表的显示职责,从AppComponent移到HeroesComponent组件中。


AppComponent is already dedicated to Heroes. Instead of moving anything out of AppComponent, we'll just rename it HeroesComponent and create a new AppComponent shell separately.

AppComponent的职责已经被移交给HeroesComponent了。 与其把AppComponent中所有的东西都搬过去,不如索性把它改名为HeroesComponent,然后单独创建一个新的AppComponent壳。

The steps are to rename:


app/heroes.component.ts (showing renamings only)

@Component({ selector: 'my-heroes', }) export class HeroesComponent implements OnInit { }

Create AppComponent

创建 AppComponent

The new AppComponent will be the application shell. It will have some navigation links at the top and a display area below for the pages we navigate to.

新的AppComponent将成为应用的“壳”。 它将在顶部放一些导航链接,并且把我们要导航到的页面放在下面的显示区中。

The initial steps are:


Our first draft looks like this:


import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <my-heroes></my-heroes> ` }) export class AppComponent { title = 'Tour of Heroes'; } import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HeroDetailComponent } from './hero-detail.component'; import { HeroesComponent } from './heroes.component'; import { HeroService } from './hero.service'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent, HeroDetailComponent, HeroesComponent ], providers: [ HeroService ], bootstrap: [ AppComponent ] }) export class AppModule { }
Remove HeroService from the HeroesComponent providers

Go back to the HeroesComponent and remove the HeroService from its providers array. We are promoting this service from the HeroesComponent to the root NgModule. We do not want two copies of this service at two different levels of our app.

回到HeroesComponent,并从providers数组中移除HeroService。 把它从HeroesComponent提升到根NgModule中。 我们不希望在应用的两个不同层次上存在它的两个副本

The app still runs and still displays heroes. Our refactoring of AppComponent into a new AppComponent and a HeroesComponent worked! We have done no harm.

应用仍然在运行,并显示着英雄列表。 我们把AppComponent重构成了一个新的AppComponentHeroesComponent,它们工作得很好! 我们毫发无损的完成了这次重构。

Add Routing


We're ready to take the next step. Instead of displaying heroes automatically, we'd like to show them after the user clicks a button. In other words, we'd like to navigate to the list of heroes.

我们已准备好开始下一步。 我们希望在用户点击按钮之后才显示英雄列表,而不是自动显示。 换句话说,我们希望“导航”到英雄列表。

We'll need the Angular Router.

我们需要 Angular 路由器

The Angular router is an external, optional Angular NgModule called RouterModule. The router is a combination of multiple provided services (RouterModule), multiple directives (RouterOutlet, RouterLink, RouterLinkActive), and a configuration (Routes). We'll configure our routes first.

Angular 路由器是一个可选的外部 Angular NgModule,名叫RouterModule。 路由器包含了多种服务(RouterModule)、多种指令(RouterOutlet、RouterLink、RouterLinkActive)、 和一套配置(Routes)。我们将先配置路由。

Add the base tag

设置 base 标签

Open index.html and add <base href="/"> at the top of the <head> section.

打开index.html并且在<head>区的顶部添加<base href="/">语句。

index.html (base-href)

<head> <base href="/">
base href is essential
base href是不可或缺的

See the base href section of the Router chapter to learn why this matters.

查看路由器一章的 base href 部分,了解为何如此。

Configure routes


Our application doesn't have any routes yet. We'll start by creating a configuration for the application routes.


Routes tell the router which views to display when a user clicks a link or pastes a URL into the browser address bar.

路由告诉路由器,当用户点击链接或者把 URL 粘贴到浏览器地址栏时,应该显示哪个视图。

Let's define our first route as a route to the heroes component:


app/app.module.ts (heroes route)

import { RouterModule } from '@angular/router'; RouterModule.forRoot([ { path: 'heroes', component: HeroesComponent } ])

The Routes are an array of route definitions. We have only one route definition at the moment but rest assured, we'll add more.

这个Routes是一个路由定义的数组。 此时,我们只有一个路由定义,但别急,后面还会添加更多。

This route definition has the following parts:


Learn more about defining routes with Routes in the Routing chapter.


Make the router available


We've setup the initial route configuration. Now we'll add it to our AppModule. We'll add our configured RouterModule to the AppModule imports array.


app/app.module.ts (app routing)

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { HeroDetailComponent } from './hero-detail.component'; import { HeroesComponent } from './heroes.component'; import { HeroService } from './hero.service'; @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule.forRoot([ { path: 'heroes', component: HeroesComponent } ]) ], declarations: [ AppComponent, HeroDetailComponent, HeroesComponent ], providers: [ HeroService ], bootstrap: [ AppComponent ] }) export class AppModule { }

We use the forRoot method because we're providing a configured router at the root of the application. The forRoot method gives us the Router service providers and directives needed for routing, and performs the initial navigation based on the current browser URL.

这里使用了forRoot方法,因为我们在应用根部提供配置的路由器。 forRoot方法提供了路由需要的路由服务提供商和指令,并基于当前浏览器 URL 初始化导航。

Router Outlet


If we paste the path, /heroes, into the browser address bar, the router should match it to the heroes route and display the HeroesComponent. But where?

如果我们把路径/heroes粘贴到浏览器的地址栏,路由器会匹配到'Heroes'路由,并显示HeroesComponent组件。 但问题是,该把它显示在哪呢?

We have to tell it where by adding a <router-outlet> element to the bottom of the template. RouterOutlet is one of the directives provided by the RouterModule. The router displays each component immediately below the <router-outlet> as we navigate through the application.

我们必须告诉它位置,所以我们把<router-outlet>标签添加到模板的底部。 RouterOutletRouterModule提供的指令之一。 当我们在应用中导航时,路由器就把激活的组件显示在<router-outlet>里面。


We don't really expect users to paste a route URL into the address bar. We add an anchor tag to the template which, when clicked, triggers navigation to the HeroesComponent.

我们当然不会真让用户往地址栏中粘贴路由的 URL, 而应该在模板中的什么地方添加一个锚标签。点击时,就会导航到HeroesComponent组件。

The revised template looks like this:


app/app.component.ts (template-v2)

template: ` <h1>{{title}}</h1> <a routerLink="/heroes">Heroes</a> <router-outlet></router-outlet> `

Notice the routerLink binding in the anchor tag. We bind the RouterLink directive (another of the RouterModule directives) to a string that tells the router where to navigate when the user clicks the link.

注意,锚标签中的[routerLink]绑定。 我们把RouterLink指令(ROUTER_DIRECTIVES中的另一个指令)绑定到一个字符串。 它将告诉路由器,当用户点击这个链接时,应该导航到哪里。

Since our link is not dynamic, we define a routing instruction with a one-time binding to our route path. Looking back at the route configuration, we confirm that '/heroes' is the path of the route to the HeroesComponent.

由于这个链接不是动态的,我们只要用一次性绑定的方式绑定到路由的路径 (path) 就行了。 回来看路由配置表,我们清楚的看到,这个路径 —— '/heroes'就是指向HeroesComponent的那个路由的路径。

Learn more about dynamic router links and the link parameters array in the Routing chapter.


Refresh the browser. We see only the app title and heroes link. We don't see the heroes list.


The browser's address bar shows /. The route path to HeroesComponent is /heroes, not /. We don't have a route that matches the path /, so there is nothing to show. That's something we'll want to fix.

浏览器的地址栏显示的是/。而到HeroesComponent的路由中的路径是/heroes,不是/。 我们没有任何路由能匹配当前的路径/,所以,自然没啥可显示的。 接下来,我们就修复这个问题。

We click the Heroes navigation link, the browser bar updates to /heroes, and now we see the list of heroes. We are navigating at last!


At this stage, our AppComponent looks like this.


app/app.component.ts (v2)

import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> <a routerLink="/heroes">Heroes</a> <router-outlet></router-outlet> ` }) export class AppComponent { title = 'Tour of Heroes'; }

The AppComponent is now attached to a router and displaying routed views. For this reason and to distinguish it from other kinds of components, we call this type of component a Router Component.

AppComponent现在加上了路由器,并能显示路由到的视图了。 因此,为了把它从其它种类的组件中区分出来,我们称这类组件为路由器组件

Add a Dashboard


Routing only makes sense when we have multiple views. We need another view.


Create a placeholder DashboardComponent that gives us something to navigate to and from.


app/dashboard.component.ts (v1)

import { Component } from '@angular/core'; @Component({ selector: 'my-dashboard', template: '<h3>My Dashboard</h3>' }) export class DashboardComponent { }

We’ll come back and make it more useful later.


Configure the dashboard route


Go back to app.module.ts and teach it to navigate to the dashboard.


Import the dashboard component and add the following route definition to the Routes array of definitions.


app/app.module.ts (Dashboard route)

{ path: 'dashboard', component: DashboardComponent },

Also import and add DashboardComponent to our AppModule's declarations.


app/app.module.ts (dashboard)

declarations: [ AppComponent, DashboardComponent, HeroDetailComponent, HeroesComponent ],



We want the app to show the dashboard when it starts and we want to see a nice URL in the browser address bar that says /dashboard. Remember that the browser launches with / in the address bar.

我们希望在应用启动的时候就显示仪表盘,而且我们希望在浏览器的地址栏看到一个好看的 URL,比如/dashboard。 记住,浏览器启动时,在地址栏中使用的路径是/

We can use a redirect route to make this happen. Add the following to our array of route definitions:


app/app.module.ts (redirect)

{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },

Learn about the redirects in the Routing chapter.


Add navigation to the template


Finally, add a dashboard navigation link to the template, just above the Heroes link.


app/app.component.ts (template-v3)

template: ` <h1>{{title}}</h1> <nav> <a routerLink="/dashboard">Dashboard</a> <a routerLink="/heroes">Heroes</a> </nav> <router-outlet></router-outlet> `

We nested the two links within <nav> tags. They don't do anything yet but they'll be convenient when we style the links a little later in the chapter.

我们在<nav>标签中放了两个链接。 它们现在还没有作用,但稍后,当我们对这些链接添加样式时,会显得比较方便。

To see these changes in your browser, go to the application root (/) and reload. The app displays the dashboard and we can navigate between the dashboard and the heroes.


Dashboard Top Heroes


Let’s spice up the dashboard by displaying the top four heroes at a glance.


Replace the template metadata with a templateUrl property that points to a new template file.


Set the moduleId property to module.id for module-relative loading of the templateUrl.


app/dashboard.component.ts (metadata)

@Component({ moduleId: module.id, selector: 'my-dashboard', templateUrl: 'dashboard.component.html', })

Create that file with this content:



<h3>Top Heroes</h3> <div class="grid grid-pad"> <div *ngFor="let hero of heroes" class="col-1-4"> <div class="module hero"> <h4>{{hero.name}}</h4> </div> </div> </div>

We use *ngFor once again to iterate over a list of heroes and display their names. We added extra <div> elements to help with styling later in this chapter.

我们再次使用*ngFor来在英雄列表上迭代,并显示它们的名字。 还添加了一个额外的<div>元素,来帮助稍后的美化工作。

Share the HeroService

共享 HeroService

We'd like to re-use the HeroService to populate the component's heroes array.


Recall earlier in the chapter that we removed the HeroService from the providers array of HeroesComponent and added it to the providers array of AppModule.

回忆一下,在前面的章节中,我们从HeroesComponentproviders数组中移除了HeroService服务, 并把它添加到AppModuleproviders数组中。

That move created a singleton HeroService instance, available to all components of the application. Angular will inject HeroService and we'll use it here in the DashboardComponent.

这个改动创建了一个HeroService的单例对象,应用中的所有组件都可以使用它。 Angular 会把HeroService注入到DashboardComponent,我们就能在DashboardComponent中使用它了。

Get heroes


Open dashboard.component.ts and add the requisite import statements.


app/dashboard.component.ts (imports)

import { Component, OnInit } from '@angular/core'; import { Hero } from './hero'; import { HeroService } from './hero.service';

We need OnInit interface because we'll initialize the heroes in the ngOnInit method as we've done before. We need the Hero and HeroService symbols in order to reference those types.

我们需要实现OnInit接口,因为我们将在ngOnInit方法中初始化英雄数组 —— 就像上次一样。 我们需要导入Hero类和HeroService类来引用它们的数据类型。

Now implement the DashboardComponent class like this:


app/dashboard.component.ts (class)

export class DashboardComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) { } ngOnInit(): void { this.heroService.getHeroes() .then(heroes => this.heroes = heroes.slice(1, 5)); } }

We've seen this kind of logic before in the HeroesComponent:


In this dashboard we cherry-pick four heroes (2nd, 3rd, 4th, and 5th) with the Array.slice method.


Refresh the browser and see four heroes in the new dashboard.



Although we display the details of a selected hero at the bottom of the HeroesComponent, we don't yet navigate to the HeroDetailComponent in the three ways specified in our requirements:

虽然我们在HeroesComponent组件的底部显示了所选英雄的详情, 但我们从未导航HeroDetailComponent组件。我们曾在需求中指定过三种方式:

  1. from the Dashboard to a selected hero.


  2. from the Heroes list to a selected hero.


  3. from a "deep link" URL pasted into the browser address bar.

    把一个指向该英雄的“深链接” URL 粘贴到浏览器的地址栏。

Adding a hero-detail route seems like an obvious place to start.


Routing to a hero detail


We'll add a route to the HeroDetailComponent in app.module.ts where our other routes are configured.


The new route is a bit unusual in that we must tell the HeroDetailComponent which hero to show. We didn't have to tell the HeroesComponent or the DashboardComponent anything.

这个新路由的不寻常之处在于,我们必须告诉HeroDetailComponent该显示哪个英雄。 之前,我们不需要告诉HeroesComponent组件和DashboardComponent组件任何东西。

At the moment the parent HeroesComponent sets the component's hero property to a hero object with a binding like this.


<my-hero-detail [hero]="selectedHero"></my-hero-detail>

That clearly won't work in any of our routing scenarios. Certainly not the last one; we can't embed an entire hero object in the URL! Nor would we want to.

显然,在我们的任何一个路由场景中它都无法工作。 最后一种场景肯定不行,我们无法将一个完整的 hero 对象嵌入到 URL 中!不过我们本来也不想这样。

Parameterized route


We can add the hero's id to the URL. When routing to the hero whose id is 11, we could expect to see an URL such as this:

我们可以把英雄的id添加到 URL 中。当导航到一个id为 11 的英雄时,我们期望的 URL 是这样的:


The /detail/ part of that URL is constant. The trailing numeric id part changes from hero to hero. We need to represent that variable part of the route with a parameter (or token) that stands for the hero's id.

URL中的/detail/部分是固定不变的,但结尾的数字id部分会随着英雄的不同而变化。 我们要把路由中可变的那部分表示成一个参数 (parameter) 令牌 (token) ,代表英雄的id

Configure a Route with a Parameter


Here's the route definition we'll use.


app/app.module.ts (hero detail)

{ path: 'detail/:id', component: HeroDetailComponent },

The colon (:) in the path indicates that :id is a placeholder to be filled with a specific hero id when navigating to the HeroDetailComponent.

路径中的冒号 (:) 表示:id是一个占位符,当导航到这个HeroDetailComponent组件时,它将被填入一个特定英雄的id

We're finished with the application routes.


We won't add a 'Hero Detail' link to the template because users don't click a navigation link to view a particular hero. They click a hero whether that hero is displayed on the dashboard or in the heroes list.

我们没有往模板中添加一个'英雄详情',这是因为用户不会直接点击导航栏中的链接去查看一个特定的英雄。 它们只会通过在英雄列表或者仪表盘中点击来显示一个英雄。

We'll get to those hero clicks later in the chapter. There's no point in working on them until the HeroDetailComponent is ready to be navigated to.

稍后我们会响应这些英雄的点击事件。 现在对它们做什么都还没有意义,除非HeroDetailComponent已经做好了,并且能够被导航过去。

That will require an HeroDetailComponent overhaul.


Revise the HeroDetailComponent


Before we rewrite the HeroDetailComponent, let's review what it looks like now:


app/hero-detail.component.ts (current)

import { Component, Input } from '@angular/core'; import { Hero } from './hero'; @Component({ selector: 'my-hero-detail', template: ` <div *ngIf="hero"> <h2>{{hero.name}} details!</h2> <div> <label>id: </label>{{hero.id}} </div> <div> <label>name: </label> <input [(ngModel)]="hero.name" placeholder="name"/> </div> </div> ` }) export class HeroDetailComponent { @Input() hero: Hero; }

The template won't change. We'll display a hero the same way. The big changes are driven by how we get the hero.


We will no longer receive the hero in a parent component property binding. The new HeroDetailComponent should take the id parameter from the params observable in the ActivatedRoute service and use the HeroService to fetch the hero with that id.

我们不会再从父组件的属性绑定中接收英雄数据。 新的HeroDetailComponent应该从ActivatedRoute服务的可观察对象params中取得id参数, 并通过HeroService服务获取具有这个指定id的英雄数据。

First, add the requisite imports:


// Keep the Input import for now, we'll remove it later: import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import { HeroService } from './hero.service';

Let's have the ActivatedRoute service, the HeroService and the Location service injected into the constructor, saving their values in private fields:


app/hero-detail.component.ts (constructor)

constructor( private heroService: HeroService, private route: ActivatedRoute, private location: Location ) {}

Also import the switchMap operator to use later with the route parameters Observable.


app/hero-detail.component.ts (switchMap import)

import 'rxjs/add/operator/switchMap';

We tell the class that we want to implement the OnInit interface.


export class HeroDetailComponent implements OnInit {

Inside the ngOnInit lifecycle hook, we use the params observable to extract the id parameter value from the ActivatedRoute service and use the HeroService to fetch the hero with that id.

ngOnInit生命周期钩子中,我们从ActivatedRoute服务的可观察对象params中提取id参数, 并且使用HeroService来获取具有这个id的英雄数据。。

app/hero-detail.component.ts (ngOnInit)

ngOnInit(): void { this.route.params .switchMap((params: Params) => this.heroService.getHero(+params['id'])) .subscribe(hero => this.hero = hero); }

Note how the switchMap operator maps the id in the observable route parameters to a new Observable, the result of the HeroService.getHero method.

注意switchMap运算符如何将可观察的路由参数中的 id 映射到一个新的Observable, 即HeroService.getHero方法的结果。

If the user re-navigates to this component while a getHero request is still inflight, switchMap cancels that old request before calling HeroService.getHero again.

如果用户在 getHero 请求执行的过程中再次导航这个组件,switchMap 再次调用HeroService.getHero之前, 会取消之前的请求。

The hero id is a number. Route parameters are always strings. So we convert the route parameter value to a number with the JavaScript (+) operator.

英雄的id是数字,而路由参数的值总是字符串。 所以我们需要通过 JavaScript 的 (+) 操作符把路由参数的值转成数字。

Do I need to unsubscribe?


The Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so we don't need to unsubscribe from the route params Observable.

Router管理它提供的可观察对象,并使订阅局部化。当组件被销毁时,会清除 订阅,防止内存泄漏,所以我们不需要从路由参数Observable取消订阅

Add HeroService.getHero


The problem with this bit of code is that HeroService doesn't have a getHero method! We better fix that quickly before someone notices that we broke the app.


Open HeroService and add a getHero method that filters the heroes list from getHeroes by id:


app/hero.service.ts (getHero)

getHero(id: number): Promise<Hero> { return this.getHeroes() .then(heroes => heroes.find(hero => hero.id === id)); }

Let's return to the HeroDetailComponent to clean up loose ends.


Find our way back


We can navigate to the HeroDetailComponent in several ways. How do we navigate somewhere else when we're done?

我们能用多种方式导航HeroDetailComponent。 但当我们完工时,我们该导航到那里呢?

The user could click one of the two links in the AppComponent. Or click the browser's back button. We'll add a third option, a goBack method that navigates backward one step in the browser's history stack using the Location service we injected previously.

现在用户可以点击AppComponent中的两个链接,或点击浏览器的“后退”按钮。 我们来添加第三个选项:一个goBack方法,它使用之前注入的Location服务, 利用浏览器的历史堆栈,导航到上一步。

app/hero-detail.component.ts (goBack)

goBack(): void { this.location.back(); }

Going back too far could take us out of the application. That's acceptable in a demo. We'd guard against it in a real application, perhaps with the CanDeactivate guard.

回退太多步会跑出我们的应用。 在演示程序中,这算不上问题。但在真实的应用中,我们需要对此进行防范。 也许你该用CanDeactivate guard.。

Then we wire this method with an event binding to a Back button that we add to the bottom of the component template.

然后,我们通过一个事件绑定把此方法绑定到模板底部的 Back(后退)按钮上。

<button (click)="goBack()">Back</button>

Modifying the template to add this button spurs us to take one more incremental improvement and migrate the template to its own file, called hero-detail.component.html:

修改模板,添加这个按钮以提醒我们还要做更多的改进, 并把模板移到独立的hero-detail.component.html文件中去。


<div *ngIf="hero"> <h2>{{hero.name}} details!</h2> <div> <label>id: </label>{{hero.id}}</div> <div> <label>name: </label> <input [(ngModel)]="hero.name" placeholder="name" /> </div> <button (click)="goBack()">Back</button> </div>

We update the component metadata with a moduleId and a templateUrl pointing to the template file that we just created.


app/hero-detail.component.ts (metadata)

@Component({ moduleId: module.id, selector: 'my-hero-detail', templateUrl: 'hero-detail.component.html', })

Refresh the browser and see the results.


Select a Dashboard Hero


When a user selects a hero in the dashboard, the app should navigate to the HeroDetailComponent to view and edit the selected hero.


Although the dashboard heroes are presented as button-like blocks, they should behave like anchor tags. When hovering over a hero block, the target URL should display in the browser status bar and the user should be able to copy the link or open the hero detail view in a new tab.

虽然仪表盘英雄被显示为像按钮一样的方块,但是它们的行为应该像锚标签一样。 当鼠标移动到一个英雄方块上时,目标 URL 应该显示在浏览器的状态条上,用户应该能拷贝链接或者在新的浏览器标签页中打开英雄详情视图。

To achieve this effect, reopen the dashboard.component.html and replace the repeated <div *ngFor...> tags with <a> tags. The opening <a> tag looks like this:

要达到这个效果,再次打开dashboard.component.html,将用来迭代的<div *ngFor...>替换为<a>,就像这样:

app/dashboard.component.html (repeated <a> tag)

<a *ngFor="let hero of heroes" [routerLink]="['/detail', hero.id]" class="col-1-4">

Notice the [routerLink] binding.


Top level navigation in the AppComponent template has router links set to fixed paths of the destination routes, "/dashboard" and "/heroes".

AppComponent模板中的顶级导航有一些路由器链接被设置固定的路径,例如"/dashboard" and "/heroes"。

This time, we're binding to an expression containing a link parameters array. The array has two elements, the path of the destination route and a route parameter set to the value of the current hero's id.

这次,我们绑定了一个包含链接参数数组的表达式。 该数组有两个元素,目标路由和一个用来设置当前英雄的 id 值的路由参数

The two array items align with the path and :id token in the parameterized hero detail route definition we added to app.module.ts earlier in the chapter:

这两个数组项与之前在app.module.ts添加的参数化的英雄详情路由定义中的 path:id 对应。

app/app.module.ts (hero detail)

{ path: 'detail/:id', component: HeroDetailComponent },

Refresh the browser and select a hero from the dashboard; the app should navigate directly to that hero’s details.


Refactor routes to a Routing Module


Almost 20 lines of AppModule are devoted to configuring four routes. Most applications have many more routes and they add guard services to protect against unwanted or unauthorized navigations. Routing considerations could quickly dominate this module and obscure its primary purpose which is to establish key facts about the entire app for the Angular compiler.

AppModule中有将近 20 行代码是用来配置四个路由的。 绝大多数应用有更多路由,并且它们还有守卫服务来保护不希望或未授权的导航。 路由的配置可能迅速占领这个模块,并掩盖其主要目的,即为 Angular 编译器设置整个应用的关键配置。

We should refactor the routing configuration into its own class. What kind of class? The current RouterModule.forRoot() produces an Angular ModuleWithProviders which suggests that a class dedicated to routing should be some kind of module. It should be a Routing Module.

我们应该重构路由配置到它自己的类。 什么样的类呢? 当前的RouterModule.forRoot()产生一个Angular ModuleWithProviders,所以这个路由类应该是一种模块类。 它应该是一个路由模块

By convention the name of a Routing Module contains the word "Routing" and aligns with the name of the module that declares the components navigated to.

按约定,路由模块的名字应该包含 “Routing”,并与导航到的组件所在的模块的名称看齐。

Create an app-routing.module.ts file as a sibling to app.module.ts. Give it the following contents extracted from the AppModule class:



import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DashboardComponent } from './dashboard.component'; import { HeroesComponent } from './heroes.component'; import { HeroDetailComponent } from './hero-detail.component'; const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent }, { path: 'detail/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroesComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {}

Noteworthy points, typical of Routing Modules:


Update AppModule

更新 AppModule

_AppModule_Now delete the routing configuration from AppModule and import the AppRoutingModule (both with an ES import statement and by adding it to the NgModule.imports list).

现在,删除AppModule中的路由配置,并导入AppRoutingModule (使用 ES import语句导入,将它添加到NgModule.imports列表)。

Here is the revised AppModule, compared to its pre-refactor state:


import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { DashboardComponent } from './dashboard.component'; import { HeroDetailComponent } from './hero-detail.component'; import { HeroesComponent } from './heroes.component'; import { HeroService } from './hero.service'; import { AppRoutingModule } from './app-routing.module'; @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule ], declarations: [ AppComponent, DashboardComponent, HeroDetailComponent, HeroesComponent ], providers: [ HeroService ], bootstrap: [ AppComponent ] }) export class AppModule { } import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { HeroDetailComponent } from './hero-detail.component'; import { DashboardComponent } from './dashboard.component'; import { HeroesComponent } from './heroes.component'; import { HeroService } from './hero.service'; @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule.forRoot([ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent }, { path: 'detail/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroesComponent } ]) ], declarations: [ AppComponent, DashboardComponent, HeroDetailComponent, HeroesComponent ], providers: [ HeroService ], bootstrap: [ AppComponent ] }) export class AppModule { }

It's simpler and focused on identifying the key pieces of the application.它更简单,专注于确定应用的关键部分。

Select a Hero in the HeroesComponent

HeroesComponent 中选择一位英雄

Earlier we added the ability to select a hero from the dashboard. We'll do something similar in the HeroesComponent.

之前我们添加了从仪表盘选择一个英雄的功能。 我们现在要做的事和HeroesComponent中很像。

The HeroesComponent template exhibits a "master/detail" style with the list of heroes at the top and details of the selected hero below.


app/heroes.component.ts (current template)

template: ` <h1>{{title}}</h1> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <my-hero-detail [hero]="selectedHero"></my-hero-detail> `,

Our goal is to move the detail to its own view and navigate to it when the user decides to edit a selected hero.


Delete the <h1> at the top (we forgot about it during the AppComponent-to-HeroesComponent conversion).


Delete the last line of the template with the <my-hero-detail> tags.


We'll no longer show the full HeroDetailComponent here. We're going to display the hero detail on its own page and route to it as we did in the dashboard.

我们不在这里显示完整的HeroDetailComponent。 我们要在它自己的页面中显示英雄详情,并像我们在仪表盘中所做的那样路由到它。

We'll throw in a small twist for variety. We are keeping the "master/detail" style but shrinking the detail to a "mini", read-only version. When the user selects a hero from the list, we don't go to the detail page. We show a mini-detail on this page instead and make the user click a button to navigate to the full detail page.

但是,我们要做一点小小的改动。 我们保持这种主从风格,把英雄详情缩小成一个 "mini" 的只读版本。 当用户从这个列表中选择一个英雄时,我们不会直接跳转到详情页。 而是在当前页中显示一个 mini 版英雄详情,当用户点击一个按钮时,才导航到完整版英雄详情页。

Add the mini-detail

添加 mini 版英雄详情

Add the following HTML fragment at the bottom of the template where the <my-hero-detail> used to be:

在模板底部原来放<my-hero-detail>的地方添加下列 HTML 片段:

<div *ngIf="selectedHero"> <h2> {{selectedHero.name | uppercase}} is my hero </h2> <button (click)="gotoDetail()">View Details</button> </div>

After clicking a hero, the user should see something like this below the hero list:



Format with the uppercase pipe


Notice that the hero's name is displayed in CAPITAL LETTERS. That's the effect of the uppercase pipe that we slipped into the interpolation binding. Look for it right after the pipe operator ( | ).

注意,英雄的名字全被显示成大写字母。那是uppercase管道的效果,借助它,我们能干预插值表达式绑定的过程。可以管道操作符 ( | ) 后面看到它。

{{selectedHero.name | uppercase}} is my hero

Pipes are a good way to format strings, currency amounts, dates and other display data. Angular ships with several pipes and we can write our own.

管道擅长做下列工作:格式化字符串、金额、日期和其它显示数据。 Angular 自带了一些管道,我们也可以写自己的管道。

Learn about pipes in the Pipes chapter.


Move content out of the component file


We are not done. We still have to update the component class to support navigation to the HeroDetailComponent when the user clicks the View Details button.


This component file is really big. Most of it is either template or CSS styles. It's difficult to find the component logic amidst the noise of HTML and CSS.

这个组件文件太大了。它大部分都是模板或 CSS 样式。 要想在 HTML 和 CSS 的噪音中看清组件的工作逻辑太难了。

Let's migrate the template and the styles to their own files before we make any more changes:


  1. Cut-and-paste the template contents into a new heroes.component.html file.


  2. Cut-and-paste the styles contents into a new heroes.component.css file.


  3. Set the component metadata's templateUrl and styleUrls properties to refer to both files.


  4. Set the moduleId property to module.id so that templateUrl and styleUrls are relative to the component.


The styleUrls property is an array of style file names (with paths). We could list multiple style files from different locations if we needed them.

styleUrls属性是一个由样式文件的文件名(包括路径)组成的数组。 我们还可以列出来自多个不同位置的样式文件。

app/heroes.component.ts (revised metadata)

@Component({ moduleId: module.id, selector: 'my-heroes', templateUrl: 'heroes.component.html', styleUrls: [ 'heroes.component.css' ] })

Update the HeroesComponent class.

更新 HeroesComponent

The HeroesComponent navigates to the HeroesDetailComponent in response to a button click. The button's click event is bound to a gotoDetail method that navigates imperatively by telling the router where to go.

点击按钮时,HeroesComponent导航到HeroesDetailComponent。 该按钮的点击事件被绑定到gotoDetail方法,它使用命令式的导航,告诉路由器去哪儿。

This approach requires some changes to the component class:


  1. Import the router from the Angular router library

    从 Angular 路由器库导入router

  2. Inject the router in the constructor (along with the HeroService)


  3. Implement gotoDetail by calling the router.navigate method


app/heroes.component.ts (gotoDetail)

gotoDetail(): void { this.router.navigate(['/detail', this.selectedHero.id]); }

Note that we're passing a two-element link parameters array — a path and the route parameter — to the router.navigate method just as we did in the [routerLink] binding back in the DashboardComponent. Here's the fully revised HeroesComponent class:

注意,我们将一个包含两个元素的链接参数数组 — 路径和路由参数 — 传递到router.navigate, 与之前在DashboardComponent中使用[routerLink]绑定一样。 修改完成的HeroesComponent类如下所示:

app/heroes.component.ts (class)

export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; constructor( private router: Router, private heroService: HeroService) { } getHeroes(): void { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } ngOnInit(): void { this.getHeroes(); } onSelect(hero: Hero): void { this.selectedHero = hero; } gotoDetail(): void { this.router.navigate(['/detail', this.selectedHero.id]); } }

Refresh the browser and start clicking. We can navigate around the app, from the dashboard to hero details and back, for heroes list to the mini-detail to the hero details and back to the heroes again. We can jump back and forth between the dashboard and the heroes.

刷新浏览器,并开始点击。 我们能在应用中导航:从仪表盘到英雄详情再回来,从英雄列表到 mini 版英雄详情到英雄详情,再回到英雄列表。 我们可以在仪表盘和英雄列表之间跳来跳去。

We've met all of the navigational requirements that propelled this chapter.


Styling the App


The app is functional but pretty ugly. Our creative designer team provided some CSS files to make it look better.

应用在功能上已经正常了,但还太丑。 我们富有创意的设计师团队提供了一些 CSS 文件,能让它变得好看一些。

A Dashboard with Style


The designers think we should display the dashboard heroes in a row of rectangles. They've given us ~60 lines of CSS for this purpose including some simple media queries for responsive design.

设计师认为我们应该把仪表盘的英雄们显示在一排方块中。 它们给了我们大约 60 行 CSS 来实现它,包括一些简单的媒体查询语句来实现响应式设计。

If we paste these ~60 lines into the component styles metadata, they'll completely obscure the component logic. Let's not do that. It's easier to edit CSS in a separate *.css file anyway.

如果我们把这 60 来行 CSS 粘贴到组件元数据的styles中,它们会完全淹没组件的工作逻辑。 不能这么做。在一个独立的*.css文件中编辑 CSS 当然会更简单。

Add a dashboard.component.css file to the app folder and reference that file in the component metadata's styleUrls array property like this:


app/dashboard.component.ts (styleUrls)

styleUrls: [ 'dashboard.component.css' ]

Stylish Hero Details


The designers also gave us CSS styles specifically for the HeroDetailComponent.

设计师还给了我们HeroDetailComponent特有的 CSS 风格。

Add a hero-detail.component.css to the app folder and refer to that file inside the styleUrls array as we did for DashboardComponent. Let's also remove the hero property @Input decorator and its import while we are at it.

app目录下添加hero-detail.component.css文件, 并且在styleUrls数组中引用它 —— 就像之前在DashboardComponent中做过的那样。 同时删除hero``@Input装饰器属性和它的导入语句

Here's the content for the aforementioned component CSS files.

上述组件的 CSS 文件内容如下:

label { display: inline-block; width: 3em; margin: .5em 0; color: #607D8B; font-weight: bold; } input { height: 2em; font-size: 1em; padding-left: .4em; } button { margin-top: 20px; font-family: Arial; background-color: #eee; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; cursor: hand; } button:hover { background-color: #cfd8dc; } button:disabled { background-color: #eee; color: #ccc; cursor: auto; } [class*='col-'] { float: left; padding-right: 20px; padding-bottom: 20px; } [class*='col-']:last-of-type { padding-right: 0; } a { text-decoration: none; } *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } h3 { text-align: center; margin-bottom: 0; } h4 { position: relative; } .grid { margin: 0; } .col-1-4 { width: 25%; } .module { padding: 20px; text-align: center; color: #eee; max-height: 120px; min-width: 120px; background-color: #607D8B; border-radius: 2px; } .module:hover { background-color: #EEE; cursor: pointer; color: #607d8b; } .grid-pad { padding: 10px 0; } .grid-pad > [class*='col-']:last-of-type { padding-right: 20px; } @media (max-width: 600px) { .module { font-size: 10px; max-height: 75px; } } @media (max-width: 1024px) { .grid { margin: 0; } .module { min-width: 60px; } }


The designers gave us CSS to make the navigation links in our AppComponent look more like selectable buttons. We cooperated by surrounding those links in <nav> tags.

设计师还给了我们一些 CSS,用于让AppComponent中的导航链接看起来更像可被选择的按钮。 要让它们协同工作,我们得把那些链接包含在<nav>标签中。

Add a app.component.css file to the app folder with the following content.


app/app.component.css (navigation styles)

h1 { font-size: 1.2em; color: #999; margin-bottom: 0; } h2 { font-size: 2em; margin-top: 0; padding-top: 0; } nav a { padding: 5px 10px; text-decoration: none; margin-top: 10px; display: inline-block; background-color: #eee; border-radius: 4px; } nav a:visited, a:link { color: #607D8B; } nav a:hover { color: #039be5; background-color: #CFD8DC; } nav a.active { color: #039be5; }

The routerLinkActive directive


The Angular Router provides a routerLinkActive directive we can use to add a class to the HTML navigation element whose route matches the active route. All we have to do is define the style for it. Sweet!

Angular路由器提供了routerLinkActive指令,我们可以用它来为匹配了活动路由的 HTML 导航元素自动添加一个 CSS 类。 我们唯一要做的就是为它定义样式。真好!

app/app.component.ts (active router links)

template: ` <h1>{{title}}</h1> <nav> <a routerLink="/dashboard" routerLinkActive="active">Dashboard</a> <a routerLink="/heroes" routerLinkActive="active">Heroes</a> </nav> <router-outlet></router-outlet> `,

Set the AppComponent’s styleUrls property to this CSS file.

设置AppComponentstyleUrls属性,指向这个 CSS 文件。

app/app.component.ts (styleUrls)

styleUrls: ['app.component.css'],

Global application styles


When we add styles to a component, we're keeping everything a component needs — HTML, the CSS, the code — together in one convenient place. It's pretty easy to package it all up and re-use the component somewhere else.

当我们把样式添加到组件中时,我们假定组件所需的一切 — HTML、CSS、程序代码 — 都在紧邻的地方。 这样,无论是把它们打包在一起还是在别的组件中复用它都会很容易。

We can also create styles at the application level outside of any component.


Our designers provided some basic styles to apply to elements across the entire app. These correspond to the full set of master styles that we installed earlier during setup. Here is an excerpt:

我们的设计师提供了一组基础样式,这些样式应用到的元素横跨整个应用。 它们与我们之前在开发环境时安装的整套样式对应。 下面是摘录:

styles.css (excerpt)

/* Master Styles */ h1 { color: #369; font-family: Arial, Helvetica, sans-serif; font-size: 250%; } h2, h3 { color: #444; font-family: Arial, Helvetica, sans-serif; font-weight: lighter; } body { margin: 2em; } body, input[text], button { color: #888; font-family: Cambria, Georgia; } /* . . . */ /* everywhere else */ * { font-family: Arial, Helvetica, sans-serif; }

Create the file styles.css, if it doesn't exist already. Ensure that it contains the master styles given here.

如果在根目录下没有一个名叫styles.css的文件,就添加它。 确保它包含这里给出的主样式

If necessary, also edit index.html to refer to this stylesheet.


index.html (link ref)

<link rel="stylesheet" href="styles.css">

Look at the app now. Our dashboard, heroes, and navigation links are styling!



Application structure and code


Review the sample source code in the for this chapter. Verify that we have the following structure:

回顾一下本章在线例子中范例代码。 验证我们是否已经得到了如下结构:

node_modules ...



The Road Behind


We travelled a great distance in this chapter


The Road Ahead


We have much of the foundation we need to build an application. We're still missing a key piece: remote data access.

我们有了很多用于构建应用的基石。 但我们仍然缺少很关键的一块:远程数据存取。

In the next chapter, we’ll replace our mock data with data retrieved from a server using http.

在下一章,我们将从硬编码模拟数据改为使用 http 服务从服务器获取数据。