Angular学习笔记10:路由

在工作或者学习中,有时候会遇到如下需求:

在一个页面上写一个导航,导航栏中的每一个选项都对应一个页面。就如Angular官方文档中:

(图片来自于Angular官方文档)

  • 添加一个仪表盘视图。

  • HeroesDashBoard视图之间导航。

  • 无论在哪个视图中点击一个英雄,都会导航到这个Hero的详情页。

  • 在邮件中点击一个深链接,会直接打开一个特定英雄的详情视图。

具体实现过程:

1.添加 AppRoutingModule

 
  1. bogon:demo wjy$ ng generate module app-routing --flat --module=app

  2. CREATE src/app/app-routing.module.spec.ts (308 bytes)

  3. CREATE src/app/app-routing.module.ts (194 bytes)

  4. UPDATE src/app/app.module.ts (718 bytes)

注意:

--flat 把这个文件放进了 src/app 中,而不是单独的目录中。
--module=app 告诉 CLI 把它注册到 AppModule 的 imports 数组中。

通常情况下不会在路由模块中声明组件,所以可以删除 @NgModule.declarations 并删除对 CommonModule 的引用。

在路由的模块中,通常会使用:RouterModule中的Routes类来配置路由器,所以要从@angular/router 中引入对这个两个符号的引入

添加一个 @NgModule.exports 数组,其中放上 RouterModule 。 导出 RouterModule 让路由器的相关指令可以在 AppModule 中的组件中使用。

此时的AppRoutingModule :

 
  1. import {NgModule} from '@angular/core';

  2. import {RouterModule, Routes} from '@angular/router';

  3.  
  4. @NgModule({

  5. imports: [],

  6. exports: [RouterModule],

  7. })

  8. export class AppRoutingModule {

  9. }

2.添加路由定义

路由定义 会告诉路由器,当用户点击某个链接或者在浏览器地址栏中输入某个 URL 时,要显示哪个视图。

典型的 Angular 路由(Route)有两个属性:

  • path:一个用于匹配浏览器地址栏中 URL 的字符串。

  • component:当导航到此路由时,路由器应该创建哪个组件

eg :当URL 为 localhost:8000/heroes 时,就导航到 HeroesComponent

  • 导入 HeroesComponent,以便能在 Route中引用它。 
  • 定义一个路由数组,其中的某个路由是指向这个组件的。

3.RouterModule.forRoot()

此时想要路由生效,就必须先初始化路由,使路由器开始监听浏览器地址栏的变化。

把 RouterModule 添加到 @NgModule.imports 数组中,并用 routes 来配置它。你只要调用 imports 数组中的 RouterModule.forRoot() 函数就行了

imports: [ RouterModule.forRoot(routes) ]

关于:forRoot:因为现在要在应用的顶级配置这个路由器。所以 forRoot() 方法会提供路由所需的服务提供商和指令,还会基于浏览器的当前 URL 执行首次导航。

4.添加路由出口 (RouterOutlet

打开 AppComponent 的模板,把 <app-heroes> 元素替换为 <router-outlet> 元素。

 
  1. <h1>{{title}}</h1>

  2. <router-outlet></router-outlet>

  3. <app-messages></app-messages>

在这里移除 <app-heroes>,是因为只有当用户导航到这里时,才需要显示 HeroesComponent

<router-outlet> 会告诉路由器要在哪里显示路由到的视图。

保存,刷新浏览器,在localhost:8000后面加上/heroes 就会看到之前的界面了。

5.添加路由链接 (routerLInk)

在正常的应用中,是不可能然用户去地址栏输入某些地址的,而且用户也不可能知道需要输入什么,用户应该在点击某个按钮或者超级链接的时候,是应用跳转到相应的页面,使路由器自动的去跳转。在当前的应用中:添加一个 <nav> 元素,并在其中放一个链接 <a> 元素,当点击它时,就会触发一个到 HeroesComponent 的导航。 

 
  1. <h1>{{title}}</h1>

  2. <nav>

  3. <a routerLink="/heroes">Heroes</a>

  4. </nav>

  5. <router-outlet></router-outlet>

  6. <app-messages></app-messages>

routerLink的值为 "/heroes",路由器会用它来匹配出指向 HeroesComponent 的路由。 routerLink 是 RouterLink指令的选择器,它会把用户的点击转换为路由器的导航操作。 它是RouterModule中公开的另一个指令。

保存,刷新浏览器,显示出了应用的标题和指向英雄列表的链接,但并没有显示英雄列表。

点击这个链接。地址栏变成了 /heroes,并且显示出了英雄列表。

6.添加仪表盘视图

在一个应用中,不可能只有一个页面,再有多个视图的情况下,才能使路由器更好的发挥其作用,使用 CLI 添加一个 DashboardComponent。

ng generate component dashboard

注意:CLI 生成了 DashboardComponent 的相关文件,并把它声明到 AppModule 中。

修改DashboardComponent模板文件:

 
  1. <h3>Top Heroes</h3>

  2. <div class="grid grid-pad">

  3. <a *ngFor="let hero of heroes" class="col-1-4">

  4. <div class="module hero">

  5. <h4>{{hero.name}}</h4>

  6. </div>

  7. </a>

  8. </div>

修改DashboardComponent类文件:

 
  1. import { Component, OnInit } from '@angular/core';

  2. import { Hero } from '../hero';

  3. import { HeroService } from '../hero.service';

  4.  
  5. @Component({

  6. selector: 'app-dashboard',

  7. templateUrl: './dashboard.component.html',

  8. styleUrls: [ './dashboard.component.css' ]

  9. })

  10. export class DashboardComponent implements OnInit {

  11. heroes: Hero[] = [];

  12.  
  13. constructor(private heroService: HeroService) { }

  14.  
  15. ngOnInit() {

  16. this.getHeroes();

  17. }

  18.  
  19. getHeroes(): void {

  20. this.heroService.getHeroes()

  21. .subscribe(heroes => this.heroes = heroes.slice(1, 5));

  22. }

  23. }

使DashboardComponent更好看点,增加私有样式

 
  1. [class*='col-'] {

  2. float: left;

  3. padding-right: 20px;

  4. padding-bottom: 20px;

  5. }

  6. [class*='col-']:last-of-type {

  7. padding-right: 0;

  8. }

  9. a {

  10. text-decoration: none;

  11. }

  12. *, *:after, *:before {

  13. -webkit-box-sizing: border-box;

  14. -moz-box-sizing: border-box;

  15. box-sizing: border-box;

  16. }

  17. h3 {

  18. text-align: center; margin-bottom: 0;

  19. }

  20. h4 {

  21. position: relative;

  22. }

  23. .grid {

  24. margin: 0;

  25. }

  26. .col-1-4 {

  27. width: 25%;

  28. }

  29. .module {

  30. padding: 20px;

  31. text-align: center;

  32. color: #eee;

  33. max-height: 120px;

  34. min-width: 120px;

  35. background-color: #607d8b;

  36. border-radius: 2px;

  37. }

  38. .module:hover {

  39. background-color: #eee;

  40. cursor: pointer;

  41. color: #607d8b;

  42. }

  43. .grid-pad {

  44. padding: 10px 0;

  45. }

  46. .grid-pad > [class*='col-']:last-of-type {

  47. padding-right: 20px;

  48. }

  49. @media (max-width: 600px) {

  50. .module {

  51. font-size: 10px;

  52. max-height: 75px; }

  53. }

  54. @media (max-width: 1024px) {

  55. .grid {

  56. margin: 0;

  57. }

  58. .module {

  59. min-width: 60px;

  60. }

  61. }

解释:

DashboardComponent模板用来表示由英雄名字链接组成的一个阵列。

  • *ngFor 复写器为组件的 heroes 数组中的每个条目创建了一个链接。

  • 这些链接被 dashboard.component.css 中的样式格式化成了一些色块。

DashboardComponent类和 HeroesComponent 类很像。

  • 它定义了一个 heroes 数组属性。

  • 它的构造函数希望 Angular 把 HeroService 注入到私有的 heroService 属性中。

  • 在 ngOnInit() 生命周期钩子中调用 getHeroes

这个 getHeroes 函数把要显示的英雄的数量缩减为四个(第二、第三、第四、第五)。

7.添加仪表盘路由

如果需要导航到仪表盘的视图就需要在路由器中添加一个路由。把 DashboardComponent 导入到 AppRoutingModule 中。

把一个指向 DashboardComponent 的路由添加到 AppRoutingModule.routes 数组中。

 
  1. import { DashboardComponent } from './dashboard/dashboard.component';

  2.  
  3.  
  4. ....

  5. ....

  6. ....

  7.  
  8.  
  9. const routes: Routes = [

  10. {path: 'heroes', component: HeroesComponent},

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

  12. ];

8.添加默认路由

当应用启动时,浏览器的地址栏指向了网站的根路径。 它没有匹配到任何现存路由,因此路由器也不会导航到任何地方。 <router-outlet> 下方是空白的。要让应用自动导航到这个仪表盘,请把下列路由添加到 AppRoutingModule.Routes 数组中。

 
  1. const routes: Routes = [

  2. {path: 'heroes', component: HeroesComponent},

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

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

  5. ];

这个路由会把一个与空路径“完全匹配”的 URL 重定向到路径为 '/dashboard' 的路由。

浏览器刷新之后,路由器加载了 DashboardComponent,并且浏览器的地址栏会显示出 /dashboard 这个 URL。

9.把仪表盘链接添加到壳组件中

在这个应用中应该允许用户通过点击页面顶部导航区的各个链接在 DashboardComponent 和 HeroesComponent 之间来回导航。

把仪表盘的导航链接添加到壳组件 AppComponent 的模板中,就放在 Heroes 链接的前面。

 
  1. <h1>{{title}}</h1>

  2. <nav>

  3. <a routerLink="/dashboard">Dashboard</a>

  4. <a routerLink="/heroes">Heroes</a>

  5. </nav>

  6. <router-outlet></router-outlet>

  7. <app-messages></app-messages>

保存,刷新浏览器,你就能通过点击这些链接在这两个视图之间自由导航了。

11.导航到英雄详情

HeroDetailComponent 可以显示所选英雄的详情。 此刻,HeroDetailsComponent 只能在 HeroesComponent 的底部看到

用户应该能通过三种途径看到这些详情。

  1. 通过在仪表盘中点击某个英雄。

  2. 通过在英雄列表中点击某个英雄。

  3. 通过把一个“深链接” URL 粘贴到浏览器的地址栏中来指定要显示的英雄。

12.从 HeroesComponent 中删除英雄详情

打开 HeroesComponent 的模板文件(heroes/heroes.component.html),并从底部删除 <app-hero-detail> 元素。

13.添加英雄详情视图

要导航到 id 为 11 的英雄的详情视图,类似于 ~/detail/11 的 URL 将是一个不错的 URL。

打开 AppRoutingModule 并导入 HeroDetailComponent

然后把一个参数化路由添加到 AppRoutingModule.routes 数组中,它要匹配指向英雄详情视图的路径。

 
  1. import { HeroDetailComponent } from './hero-detail/hero-detail.component';

  2. ...

  3. ...

  4. ...

  5. const routes: Routes = [

  6. {path: 'heroes', component: HeroesComponent},

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

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

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

  10. ];

 注意:path 中的冒号(:)表示 :id 是一个占位符,它表示某个特定英雄的 id

14.DashboardComponent 中的英雄链接

 
  1. <h3>Top Heroes</h3>

  2. <div class="grid grid-pad">

  3. <a *ngFor="let hero of heroes" class="col-1-4"

  4. routerLink="/detail/{{hero.id}}">

  5. <div class="module hero">

  6. <h4>{{hero.name}}</h4>

  7. </div>

  8. </a>

  9. </div>

15.HeroesComponent 中的英雄链接

 
  1. <h2>My Heroes</h2>

  2. <ul class="heroes">

  3. <li *ngFor="let hero of heroes">

  4. <a routerLink="/detail/{{hero.id}}">

  5. <span class="badge">{{hero.id}}</span> {{hero.name}}

  6. </a>

  7. </li>

  8. </ul>

16.移除死代码

在这个过程中,会有一些之用到,但是现在用不到的代码,虽然代码量很少,但是最好还是将其删除。

17.支持路由的 HeroDetailComponent

当路由器会在响应形如 ~/detail/11 的 URL 时创建 HeroDetailComponent

HeroDetailComponent 需要从一种新的途径获取要显示的英雄

  • 获取创建本组件的路由,

  • 从这个路由中提取出 id

  • 通过 HeroService 从服务器上获取具有这个 id 的英雄数据。

导入需要的语句,修改构造函数,把 ActivatedRouteHeroService 和 Location 服务注入到构造函数中,将它们的值保存到私有变量里:

 
  1. import { ActivatedRoute } from '@angular/router';

  2. import { Location } from '@angular/common';

  3.  
  4. import { HeroService } from '../hero.service';

  5.  
  6. ...

  7. ...

  8. ...

  9. constructor(

  10. private route: ActivatedRoute,

  11. private heroService: HeroService,

  12. private location: Location

  13. ) {}

ActivatedRoute 保存着到这个 HeroDetailComponent 实例的路由信息。 这个组件对从 URL 中提取的路由参数感兴趣。 其中的 id 参数就是要现实的英雄的 id

HeroService 从远端服务器获取英雄数据,本组件将使用它来获取要显示的英雄

location 是一个 Angular 的服务,用来与浏览器打交道。

18.从路由参数中提取 id

 
  1. ngOnInit(): void {

  2. this.getHero();

  3. }

  4.  
  5. getHero(): void {

  6. const id = +this.route.snapshot.paramMap.get('id');

  7. this.heroService.getHero(id)

  8. .subscribe(hero => this.hero = hero);

  9. }

route.snapshot 是一个路由信息的静态快照,抓取自组件刚刚创建完毕之后。

paramMap 是一个从 URL 中提取的路由参数值的字典。 "id" 对应的值就是要获取的英雄的 id

路由参数总会是字符串。 JavaScript 的 (+) 操作符会把字符串转换成数字,英雄的 id 就是数字类型。

刷新浏览器,应用挂了。出现一个编译错误,因为 HeroService 没有一个名叫 getHero() 的方法。

19.添加 HeroService.getHero()

 
  1. getHero(id: number): Observable<Hero> {

  2. this.messageService.add(`HeroService: fetched hero id=${id}`);

  3. return of(HEROES.find(hero => hero.id === id));

  4. }

注意:反引号 ( ` ) 用于定义 JavaScript 的 模板字符串字面量,以便嵌入 id

getHero() 也有一个异步函数签名。 它用 RxJS 的 of() 函数返回一个 Observable 形式的模拟英雄数据。

将来可以用一个真实的 Http 请求来重现实现 getHero(),而不用修改调用了它的 HeroDetailComponent

保存,刷新浏览器,应用又恢复正常了。 你可以在仪表盘或英雄列表中点击一个英雄来导航到该英雄的详情视图。

20.回到原路

通过点击浏览器的后退按钮,你可以回到英雄列表或仪表盘视图,这取决于你从哪里进入的详情视图。

如果能在 HeroDetail 视图中也有这么一个按钮就更好了。

把一个后退按钮添加到组件模板的底部,并且把它绑定到组件的 goBack() 方法。

src/app/hero-detail/hero-detail.component.html (back button)

<button (click)="goBack()">go back</button>

在组件类中添加一个 goBack() 方法,利用你以前注入的 Location 服务在浏览器的历史栈中后退一步。

 
  1. goBack(): void {

  2. this.location.back();

  3. }

21.增加一些样式,使页面更好看。

AppComponent

 
  1. h1 {

  2. font-size: 1.2em;

  3. color: #999;

  4. margin-bottom: 0;

  5. }

  6. h2 {

  7. font-size: 2em;

  8. margin-top: 0;

  9. padding-top: 0;

  10. }

  11. nav a {

  12. padding: 5px 10px;

  13. text-decoration: none;

  14. margin-top: 10px;

  15. display: inline-block;

  16. background-color: #eee;

  17. border-radius: 4px;

  18. }

  19. nav a:visited, a:link {

  20. color: #607d8b;

  21. }

  22. nav a:hover {

  23. color: #039be5;

  24. background-color: #cfd8dc;

  25. }

  26. nav a.active {

  27. color: #039be5;

  28. }

DashboardComponent

 
  1. [class*='col-'] {

  2. float: left;

  3. padding-right: 20px;

  4. padding-bottom: 20px;

  5. }

  6. [class*='col-']:last-of-type {

  7. padding-right: 0;

  8. }

  9. a {

  10. text-decoration: none;

  11. }

  12. *, *:after, *:before {

  13. -webkit-box-sizing: border-box;

  14. -moz-box-sizing: border-box;

  15. box-sizing: border-box;

  16. }

  17. h3 {

  18. text-align: center; margin-bottom: 0;

  19. }

  20. h4 {

  21. position: relative;

  22. }

  23. .grid {

  24. margin: 0;

  25. }

  26. .col-1-4 {

  27. width: 25%;

  28. }

  29. .module {

  30. padding: 20px;

  31. text-align: center;

  32. color: #eee;

  33. max-height: 120px;

  34. min-width: 120px;

  35. background-color: #607d8b;

  36. border-radius: 2px;

  37. }

  38. .module:hover {

  39. background-color: #eee;

  40. cursor: pointer;

  41. color: #607d8b;

  42. }

  43. .grid-pad {

  44. padding: 10px 0;

  45. }

  46. .grid-pad > [class*='col-']:last-of-type {

  47. padding-right: 20px;

  48. }

  49. @media (max-width: 600px) {

  50. .module {

  51. font-size: 10px;

  52. max-height: 75px; }

  53. }

  54. @media (max-width: 1024px) {

  55. .grid {

  56. margin: 0;

  57. }

  58. .module {

  59. min-width: 60px;

  60. }

  61. }

HeroesComponent

 
  1. .heroes {

  2. margin: 0 0 2em 0;

  3. list-style-type: none;

  4. padding: 0;

  5. width: 15em;

  6. }

  7. .heroes li {

  8. position: relative;

  9. cursor: pointer;

  10. background-color: #EEE;

  11. margin: .5em;

  12. padding: .3em 0;

  13. height: 1.6em;

  14. border-radius: 4px;

  15. }

  16.  
  17. .heroes li:hover {

  18. color: #607D8B;

  19. background-color: #DDD;

  20. left: .1em;

  21. }

  22.  
  23. .heroes a {

  24. color: #888;

  25. text-decoration: none;

  26. position: relative;

  27. display: block;

  28. width: 250px;

  29. }

  30.  
  31. .heroes a:hover {

  32. color:#607D8B;

  33. }

  34.  
  35. .heroes .badge {

  36. display: inline-block;

  37. font-size: small;

  38. color: white;

  39. padding: 0.8em 0.7em 0 0.7em;

  40. background-color: #607D8B;

  41. line-height: 1em;

  42. position: relative;

  43. left: -1px;

  44. top: -4px;

  45. height: 1.8em;

  46. min-width: 16px;

  47. text-align: right;

  48. margin-right: .8em;

  49. border-radius: 4px 0 0 4px;

  50. }

HeroDetailComponent

 
  1. label {

  2. display: inline-block;

  3. width: 3em;

  4. margin: .5em 0;

  5. color: #607D8B;

  6. font-weight: bold;

  7. }

  8. input {

  9. height: 2em;

  10. font-size: 1em;

  11. padding-left: .4em;

  12. }

  13. button {

  14. margin-top: 20px;

  15. font-family: Arial;

  16. background-color: #eee;

  17. border: none;

  18. padding: 5px 10px;

  19. border-radius: 4px;

  20. cursor: pointer; cursor: hand;

  21. }

  22. button:hover {

  23. background-color: #cfd8dc;

  24. }

  25. button:disabled {

  26. background-color: #eee;

  27. color: #ccc;

  28. cursor: auto;

  29. }

猜你喜欢

转载自blog.csdn.net/plpldog/article/details/82992637