为什么 Angular 2+ Router 路由定义 Javascript 对象而不是 Typescript 类?

Why are Angular 2+ Router route definitions Javascript Objects instead of Typescript Classes?

Angular 2+ 路由器的默认使用涉及将路由定义添加到应用程序路由模块。

应用-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AboutComponent } from './pages/about/about.component';
import { HomeComponent } from './pages/home/home.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '', component: HomeComponent},
  { path: '**', pathMatch: 'full', component: HomeComponent},
];

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

这些以 { path: '[path]', component: '[componentName]' } 的形式添加为 Javascript 个对象。但是,规定的最佳实践是在组件外部定义数据。 (这个Angular.io tutorial提供了一个很好的例子)

我们看不到“routeDefinition”打字稿有什么原因吗class?像这样:

路线-definition.ts

 export class RouteDefinition {
    constructor(
        public path: string,
        public component: string) {}

    //Add additional constructors as needed
}

然后代替

{ path: '[path]', component '[component]' } 

你会用

实现它
new Route ('[path]', '[component]')

如果没有原因,创建和使用此 class 是否违反最佳实践? (我知道我可以在自己的项目中做任何我想做的事,但我发现无论在哪里定义最佳实践都非常有用。)

嗯,你的建议和实现已经是一样的了。如您所见,Routes type and it is an alias for Route[], whereas the Route interface 包含路由定义的所有可能字段。