在 Angular 应用中添加路由支持可以让你创建一个更具交互性和导航性的单页面应用。下面是一个简单的教程,演示如何为一个名为 "英雄之旅"(Tour of Heroes)的应用添加路由。

步骤 1: 创建新的 Angular 项目

使用 Angular CLI 创建一个新的 Angular 项目:
ng new tour-of-heroes
cd tour-of-heroes

步骤 2: 创建英雄组件

使用 Angular CLI 创建两个简单的组件,分别表示英雄列表和英雄详情:
ng generate component hero-list
ng generate component hero-detail

步骤 3: 安装 Angular 路由模块

安装 Angular 的路由模块:
ng add @angular/router

步骤 4: 配置路由

打开 src/app/app-routing.module.ts 文件,配置路由:
// app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroListComponent } from './hero-list/hero-list.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';

const routes: Routes = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroListComponent },
  { path: 'heroes/:id', component: HeroDetailComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

步骤 5: 在模板中使用路由链接

打开 src/app/app.component.html 文件,并在模板中使用 routerLink 指令创建导航链接:
<!-- app.component.html -->

<nav>
  <a routerLink="/heroes">Heroes</a>
</nav>

<router-outlet></router-outlet>

步骤 6: 在模板中显示视图

打开 src/app/hero-list/hero-list.component.html 文件和 src/app/hero-detail/hero-detail.component.html 文件,并分别添加一些内容,以便在视图中显示一些信息。
<!-- hero-list.component.html -->

<div *ngFor="let hero of heroes">
  <a [routerLink]="['/heroes', hero.id]">{{ hero.name }}</a>
</div>
<!-- hero-detail.component.html -->

<div *ngIf="hero">
  <h2>{{ hero.name }}</h2>
  <p>{{ hero.description }}</p>
</div>

步骤 7: 在组件中处理路由参数

打开 src/app/hero-detail/hero-detail.component.ts 文件,并在组件中使用 ActivatedRoute 来处理路由参数:
// hero-detail.component.ts

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

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css'],
})
export class HeroDetailComponent implements OnInit {
  hero: Hero;

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    // Fetch the hero with the given id from your service or another data source
    // For simplicity, we'll use a hardcoded hero array here
    this.hero = { id, name: `Hero ${id}`, description: `Description of Hero ${id}` };
  }
}

步骤 8: 启动应用

最后,运行你的应用:
ng serve

访问 http://localhost:4200,你应该能够看到应用并通过导航链接在不同的视图之间切换,查看英雄列表和英雄详情。

这个例子演示了如何为 "英雄之旅" 应用添加路由支持。你可以根据实际需求扩展和修改路由配置,以构建更复杂的导航结构和功能。


转载请注明出处:http://www.pingtaimeng.com/article/detail/4940/Angular