为什么在尝试设置页面标题时出现此错误?

Why I get this error trying to set page title?

官方文档告诉我们使用title 属性 of Route来设置页面标题。 https://angular.io/guide/router#setting-the-page-title

Each page in your application should have a unique title so that they can be identified in the browser history. The Router sets the document's title using the title property from the Route config.

但是我得到这个错误:

Type '{ path: string; title: string; component: typeof SecondComponent; }' is not assignable to type 'Route'. Object literal may only specify known properties, and 'title' does not exist in type 'Route'.

import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { SingleComponent } from './single/single.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FirstComponent } from './first/first.component';
import { SecondComponent } from './second/second.component';
import { ChildAComponent } from './child-a/child-a.component';
import { ChildBComponent } from './child-b/child-b.component';

const routes: Routes = [
  { path: 'first', component: FirstComponent, children: [
      { path: 'child-a', component: ChildAComponent },
      { path: 'child-b', component: ChildBComponent },
  ]},
  { path: 'second', title: 'Second page title', component: SecondComponent }, // here an error
  { path: 'single', component: SingleComponent },
  { path: '', redirectTo: '/first', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent },
];


@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

您正在尝试使用 Angular 14 的路由 API,实际上它仅处于测试阶段:)

在14版本下,如果要设置页面标题,必须使用data属性并设置一个属性“标题”,如:

{
   path: 'tralala',
   component: TralalaComponent,
   data: {
      title: 'My Title'
   }
}

然后,在您的页面组件 (TraralaComponent) 中,注入 Angular 的 TitleService and the ActivatedRoute 以检索 data object,获取您的标题并设置它。

export class TralalaComponent implement OnInit {
    constructor(
        private readonly route: ActivatedRoute,
        private readonly titleService: Title
    ) {}

    ngOnInit(): void {
      this.titleService.setTitle(this.route.snapshot.data['title'])
    }
}

在 Angular 13 中 属性 无法识别标题。请参阅 API reference here. But it is in Angular 14。所以你的代码将在 Angular 14 上运行,但在 13

上不起作用