背景和问题
我在app-routing.module
中定义了几条路由,如下所示:
// imports
const routes: Routes = [
{ path: 'home', title: 'Home Route', component: HomeComponent },
{ path: 'other', title: 'Other Route', component: OtherComponent},
{ path: 'another', title: 'Yet Another Route', component: YetAnotherComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
];
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我还定义了一个navigation-title.component
,我想用它来显示当前的路线,例如"My App | Home Route"
或"My App | Other Route"
。
然而,似乎没有一种直接的方式来绑定到路线标题。
我尝试过的事情
正在将ActivatedRoute
注入到我的navigation-title
组件中
我第一次尝试用async
管道注入一个private activatedRoute: ActivatedRoute
并绑定到this.activatedRoute.title
(它是一个Observable<string | undefined>
),但是这个激活的路径在您导航时实际上似乎没有改变。
挂接到路由器导航事件
接下来,我尝试订阅路由器事件,特别是订阅NavigationEnd
,以便更新标题,但是在导航结束时从激活的路线中检索标题总是导致获得上一条路线的标题。
绑定路由器插座
最后,我使用一些代码将router-outlet
的(activate)
事件绑定到navigation-title.component
内部的事件处理程序(有关更多详细信息,请参见this gist),但不幸的是,这导致了title组件和路由器插座之间的紧密耦合。
难道没有更好的(即完全解耦的)方法来简单地从注入的Router
或ActivatedRoute
获取路线标题吗?
附言
我当然不想使用TitleService
,因为当您已经可以在生成所述组件的路由内定义页面标题时,让组件设置页面标题是没有意义的。
1条答案
按热度按时间8i9zcol21#
如果标题不是动态的,但你仍然想做一些不同的,你可以使用从Angular 14+的小标题策略
来源:https://dev.to/brandontroberts/setting-page-titles-natively-with-the-angular-router-393j