如何在包含 RouterOutlet 的 HTML 模板中直接使用激活路由的数据?

How to use the activated route's data DIRECTLY in the HTML template containing the RouterOutlet?

这个弄了我好久,所以我希望通过SO的问答方式分享解决方案来节省别人的时间。开始了:

目标

我有一个 Angular8 网络应用程序,我在其中使用 RouterModule 在组件之间导航。

我的路线是这样定义的:

const routes: Routes = [
    { path: 'moo', component: AppMooComponent, data: { title: 'Moo Section', desc: 'Moo is the first example component.' } },
    { path: 'boo', component: AppBooComponent, data: { title: 'Boo Section', desc: 'Boo is the second example component.' } },
    { path: 'foo', component: AppFooComponent, data: { title: 'Foo Section', desc: 'Foo is the third example component.' } },
    { path: '', redirectTo: 'moo', pathMatch: 'full' },
];

我希望能够通过以下方式在我的 HTML 模板中使用 data.titledata.desc(或与此相关的任何已定义数据):

<ul>
    <li><a [routerLink]="['moo']">Moo</a></li>
    <li><a [routerLink]="['boo']">Boo</a></li>
    <li><a [routerLink]="['foo']">Foo</a></li>
</ul>
<hr>
<h1>{{<something>.data.title}}</h1>
<p>{{<something>.data.desc}}</p>
<hr>
<router-outlet></router-outlet>

问题

注入ActivatedRoute获取数据是不行的,因为ActivatedRoute是:

A service that is provided to each route component

并且包含 router-outlet 的组件不是路由组件。

研究

我搜索了该站点,发现以下问题讨论了一个非常相似的问题:

Get route data outside the router outlet

Access activated route data from some other component

然而,在我的例子中,重点是 在 HTML 模板 中直接使用路线数据,因此这些可能的解决方案都不合适(如总结在 How To Get Route Path Parameters In Non-Routed Angular Components):


如何以理想的方式实现?

解决方案

我建议您使用 template variable reference,如文档中所示:

#myTemplateVar="outlet"

然后您可以通过 <router-outlet>activatedRouteData: Data 属性 访问路由数据,并像这样在 HTML 模板中使用它:

<h1>{{myTemplateVar.activatedRouteData.title}}</h1>
<p>{{myTemplateVar.activatedRouteData.desc}}</p>
<hr>
<router-outlet #myTemplateVar="outlet"></router-outlet>

例子

我在 Stackblitz 上为您准备了一个简单示例,以演示所提出的解决方案。

结果

结果如下(另一个routes/components相似):