The default use of the Angular 2+ Router involves adding route definitions to the app-routing module.
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 { }
These are added as Javascript Objects in the form { path: '[path]', component: '[componentName]' }
. However, the stated best-practice is to define data outside of the component. (This Angular.io tutorial provides a good example)
Is there a reason we don't see a "routeDefinition" typescript class? Something like this:
export class RouteDefinition {
constructor(
public path: string,
public component: string) {}
//Add additional constructors as needed
}
Then instead of
{ path: '[path]', component '[component]' }
you would implement it with
new Route ('[path]', '[component]')
If there is not a reason, would it be against best practice to create and use this class? (I know I can do whatever I would like to in my own projects, but I find it very useful to stick to best practices wherever they are defined.)
Well, what you are suggesting is already the same with the implementation. As you can see there is a Routes type and it is an alias for Route[], whereas the Route interface contains all possible fields for a Route definition.