M. Al Jumaily
M. Al Jumaily

Reputation: 973

TypeScript/Angular: Adding an interface to data property in router

In the app-routing-module.ts file, we can use the data property to insert our customized fields/variables like so:

...
{
  path: 'admin-board',
  loadChildren: './admin-board/admin-board.module#AdminBoardPageModule',
  data: {
    role: 'admin'
  }
},
...

My question is that can we add an interface inside the data property? Something similar to:

import { Role } from './role';
...
{
  path: 'admin-board',
  loadChildren: './admin-board/admin-board.module#AdminBoardPageModule',
  data: {
    role: Role = { 
      user: false, 
      admin: true 
    };
  }
},
...

It does give the following error:

'Role' only refers to a type, but is being used as a value here.ts(2693)

The fix that I came up with is removing Role = yielding:

import { Role } from './role';
...
{
  path: 'admin-board',
  loadChildren: './admin-board/admin-board.module#AdminBoardPageModule',
  data: {
    role: { 
      user: false, 
      admin: true 
    };
  }
},
...

but this defeats the whole purpose as I am trying to associate role with the interface Role.

I should also mention that I have checked the official documentation of a router and couldn't find anything that helps my situation.

Upvotes: 0

Views: 613

Answers (2)

Pace
Pace

Reputation: 43937

You can do this. I'm not certain if it will achieve your goals:

import { Role } from './role';
...
{
  path: 'admin-board',
  loadChildren: './admin-board/admin-board.module#AdminBoardPageModule',
  data: {
    role: <Role> { 
      user: false, 
      admin: true 
    };
  }
},
...

Upvotes: 1

Y_Moshe
Y_Moshe

Reputation: 432

You cannot do it, no way - my opinion because data is an Object key/value sperate by ":" and to define a type in TS it's done by the ":' so .....

but what u can do is where u accessed it from a component u can do the following to get the IntelliSense:

const role: Role = this.route.snapshot.data['role'] as Role;

I hope it helps.

Upvotes: 2

Related Questions