Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing type-safe route data to routes in angular 2

In my routing module I am passing data in this fashion.

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent, data: { ShowTopBar: true, showSideBar: false} },
  { path: 'error', component: ErrorComponent, data: { ShowTopBar: true, showSideBar: false}}

];
export const AppRoutingModule: ModuleWithProviders = RouterModule.forRoot(routes);

In order to make the data type safe I have created a RouteData class which would hold the ShowTopBar and ShowSideBar values and initialize them through a constructor.

export class RouteData {
constructor(showTopbar: boolean, showSideBar: boolean) {
  this.ShowSideBar = showSideBar;
  this.ShowTopBar = showTopbar;
}
 public ShowTopBar: boolean;
 public ShowSideBar: boolean;
}

Now, I have changed the declarations for Routes in the following manner:

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent, data: new RouteData(false, false) },
  { path: 'error', component: ErrorComponent, data: new RouteData(true, false)}

];

which is giving the following error on compiling:

Error encountered resolving symbol values statically. Calling function 'RouteData', function calls are not supported. Consider replacing the function or la mbda with a reference to an exported function, resolving symbol AppRoutingModule

My Question is how can we pass RouteData in a type-safe way to Routes so that I can take advantage of type-safety.

like image 859
SJMan Avatar asked Nov 08 '17 08:11

SJMan


People also ask

What would you use in Angular 2 to define routes?

We use the router-outlet directive, an Angular 2 Routing directive that displays the active route (like ng-view ).


1 Answers

you can do below,

extend Route from @angular/router and update Type of data like below,

export interface RouteData {
  ShowTopBar: boolean;
  ShowSideBar: boolean;
}

interface CustomRoute extends Route {
  data?: RouteData;
}

update type of routes to CustomRoute[] from Routes

const routes: CustomRoute[] = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent, data: { ShowSideBar: true, ShowTopBar: true } }
];

now you can pass Type safe data, see below,

enter image description here

like image 93
Madhu Ranjan Avatar answered Oct 08 '22 03:10

Madhu Ranjan