【问题标题】:Why are Angular 2+ Router route definitions Javascript Objects instead of Typescript Classes?为什么 Angular 2+ 路由器路由定义是 Javascript 对象而不是 Typescript 类?
【发布时间】:2020-10-20 01:29:00
【问题描述】:

Angular 2+ 路由器的默认使用包括将路由定义添加到 app-routing 模块。

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 { }

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

我们没有看到“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]')

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

【问题讨论】:

    标签: angular typescript routes angular2-router


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多