【发布时间】:2021-03-26 07:50:36
【问题描述】:
在 Angular“英雄之旅”教程中修改我的工作时,我试图了解子路由是如何工作的。我有一个嵌入了<router-outlet></router-outlet> 的 HeroesComponent。 HeroesComponent,通过 '/heroes' 访问,显示各个英雄的链接列表,每个英雄的 routerLink 设置为 '/heroes/[id]',显示该英雄的 ID 而不是 '[id]'--'/例如 heros/7'。
(我知道如何在不使用子路由的情况下将子组件直接添加到父组件。我在这里的目的是了解子路由是如何工作的。对于直接子组件,我知道使用 ngOnChanges,但在这种情况下改变的不是 @Input 组件属性,而是路由器属性。)
路由
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'heroes', component: HeroesComponent, runGuardsAndResolvers: 'always', children: [
{ path: ':id', component: HeroDetailComponent, runGuardsAndResolvers: 'always' }
] },
{ path: 'dashboard', component: DashboardComponent }
];
父 HeroesComponent 中的子路由器出口
<section>
<h2>All Heroes</h2>
<div><a routerLink="/detail">Create a hero</a></div>
<table class="table">
<thead>
<tr><th>Name</th><th>Location</th></tr>
</thead>
<tbody>
<tr *ngFor="let hero of heroes">
<th><a routerLink="/heroes/{{hero.id}}">{{hero.name}}</a></th>
<td>{{hero.location}}</td>
<td><a (click)="delete(hero.id)">delete</a></td>
</tr>
</tbody>
</table>
</section>
<router-outlet></router-outlet>
子 HeroDetailComponent 中的关键代码
ngOnInit(): void {
let id: string;
// I'll explain this comment later.
// this.route.paramMap.subscribe((paramMap) => id = paramMap.get('id'));
id = this.route.snapshot.paramMap.get('id');
if (id) {
this.mode = 'update';
this.heroService.getHero(+id).subscribe((hero) => {
this.hero = hero
});
} else {
this.mode = 'add';
this.hero = { id: 0, name: '', location: '', cuisine: 0 }
}
}
导航到 /heroes 给了我以下信息。 (我已经为 .NET CORE 教程设置了餐厅 API,因此我将其重新用作本 Angular 教程的数据源。)
浏览器的地址栏显示“localhost:4200/heroes”。当我将光标悬停在“Masseria”上时,浏览器状态栏(这是 Windows 10 上的 Chrome,如果重要的话)显示“http://localhost:4200/heroes/9”。点击 Masseria 链接,我得到:
到目前为止,一切都很好! 然后,当我点击 Takumi 链接时,虽然浏览器地址字段的内容正确更改为“http://localhost:4200/heroes/13”,显示没有改变:我仍在查看 Masseria 的详细信息。
现在,如果我点击浏览器地址字段并按 Enter,然后整个页面都会刷新,同时显示餐厅列表和 Takumi 的详细信息。
我认为没有发生一些必要的更新通知。我做了一点研究。关于我在上面最后一段代码中注释掉的那行,我认为可能显式订阅路由器参数 :id 会有所帮助,使用
this.route.paramMap.subscribe((paramMap) => id = paramMap.get('id'));
而不是从路由器快照中获取参数。这没有效果。
我还尝试将属性runGuardsAndResolvers: 'always' 添加到我的路由数组中的父路径和子路径(上面的第一块代码),但这也没有效果。
【问题讨论】:
标签: angular angular2-routing nested-routes