首页 > 解决方案 > 为什么 Angular 2+ 路由器路由定义是 Javascript 对象而不是 Typescript 类?

问题描述

Angular 2+ 路由器的默认使用涉及将路由定义添加到 app-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 { }

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

我们没有看到“routeDefinition”打字稿类是有原因的吗?像这样的东西:

路由定义.ts

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

    //Add additional constructors as needed
}

然后代替

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

你会用它来实现它

new Route ('[path]', '[component]')

如果没有理由,创建和使用此类是否违反最佳实践?(我知道我可以在我自己的项目中做任何我想做的事情,但我发现在定义最佳实践的任何地方坚持最佳实践非常有用。)

标签: angulartypescriptroutesangular2-router

解决方案


好吧,您的建议已经与实施相同。如您所见,有一个Routes类型,它是 Route[] 的别名,而Route 接口包含 Route 定义的所有可能字段。


推荐阅读