Scipion Scipion - 1 month ago 9
TypeScript Question

Angular2 router: Why don't we have states anymore on routes

Here is my

app.routes
:

const routes: Routes = [
{
path: "login",
component: LoginComponent
},
{
path: "users",
component: UsersComponent
},
{
path: "error",
component: ErreurComponent
},
{
path: "more/complex/path",
component: FooComponent
},
{
path: "",
component: HomepageComponent,
}
]

export const APP_ROUTER_MODULE = RouterModule.forRoot(routes)


Why can't I specify a state or a name for my routes ? If I want to know if wether or not I am on the error page, I then have to check the current route and look for what I have specified in "path" (see also my
FooComponent
above). I found this a bit silly. Is there anyway to work around this ?

Answer
const routes: Routes = [
    {
      path: "login",
      component: LoginComponent,
      data: { name: 'r1'}
    },
    {
      path: "users",
      component: UsersComponent,
      data: { name: 'r2'}
    },
    {
      path: "error",
      component: ErreurComponent,
      data: { name: 'r3'}
    },
    {
      path: "more/complex/path",
      component: FooComponent,
      data: { name: 'r4'}
    },
    {
      path: "",
      component: HomepageComponent,
      data: { name: 'r5'}
    }
]
class SomeComponent {
  constructor(route:ActivatedRoute) {
    route.data.forEach(data => console.log(data['name']));
  }
}

See also How do I pass data in Angular 2 components while using Routing?