typescript 如何在导航过程中更改路线时动态获取路线的“标题”值?

r8xiu3jd  于 2023-01-21  发布在  TypeScript
关注(0)|答案(1)|浏览(137)

背景和问题

我在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组件和路由器插座之间的紧密耦合。
难道没有更好的(即完全解耦的)方法来简单地从注入的RouterActivatedRoute获取路线标题吗?

附言

我当然想使用TitleService,因为当您已经可以在生成所述组件的路由内定义页面标题时,让组件设置页面标题是没有意义的。

8i9zcol2

8i9zcol21#

如果标题不是动态的,但你仍然想做一些不同的,你可以使用从Angular 14+的小标题策略
来源:https://dev.to/brandontroberts/setting-page-titles-natively-with-the-angular-router-393j

@Injectable()
export class TemplatePageTitleStrategy extends TitleStrategy {
  constructor(private readonly title: Title) {
    super();
  }

  override updateTitle(routerState: RouterStateSnapshot) {
    const title = this.buildTitle(routerState);
    if (title !== undefined) {
      this.title.setTitle(`My App | ${title}`);
    }
  }
}
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [
    {
      provide: TitleStrategy,
      useClass: TemplatePageTitleStrategy
    }
  ]
})
export class AppRoutingModule {}

相关问题