Angular Tour of Heroes 确实使用了 Angular 路由。
在 Angular Tour of Heroes 应用程序中,路由模块被用来定义应用程序的路由。通过路由模块,我们可以指定不同 URL 路径与对应的组件之间的关系。
以下是一个示例解决方案,展示了如何在 Angular Tour of Heroes 中使用 Angular 路由。
app-routing.module.ts
的文件,并添加以下代码:import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'heroes', component: HeroesComponent },
{ path: 'detail/:id', component: HeroDetailComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
import { AppRoutingModule } from './app-routing.module';
@NgModule({
imports: [
BrowserModule,
AppRoutingModule
],
declarations: [
AppComponent,
DashboardComponent,
HeroesComponent,
HeroDetailComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
routerLink
指令来创建导航链接。例如,在 app.component.html 文件中:
ActivatedRoute
和 Router
服务来处理路由相关的逻辑。例如,在 hero-detail.component.ts 文件中:import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@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,
private router: Router,
private heroService: HeroService
) { }
ngOnInit(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.router.navigate(['/heroes']);
}
}
以上就是一个使用 Angular 路由的解决方案,其中包含了路由模块的定义、导航链接的创建以及路由相关的逻辑处理。