Lin Du
Lin Du

Reputation: 102287

How to add custom data to a route?

I want to add some custom data to route when I define the routes.

How can I do that?

like:

{
  path: 'department',
  component: DepartmentComponent,

  customdata: {
    name: 'foo',
    age: '23'
  }
}

I don't want the custom data to display in URL. I just use it internally.

Upvotes: 5

Views: 3415

Answers (2)

filipows
filipows

Reputation: 456

I do it in the following way:

{ path: 'admin', canActivate: [RoleGuard], data: { roles: ['admin'] } }

I use it to add roles custom property to the route to be able to enable access only to users with a particular role, that I'm setting in Routes.

Upvotes: 2

Max Koretskyi
Max Koretskyi

Reputation: 105497

You can define the custom data to the route like this:

[
   {path: 'inbox', data: {name: 'foo', age: 23}},
]

and read like this:

class ConversationCmp {
    constructor(r: ActivateRoute) {
         r.data.subscribe((p) => {
              console.log(p);
         });
    }
}

It's defined on the Route interface:

export interface Route {
  path?: string;
  ...
  data?: Data;
}

Upvotes: 7

Related Questions