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.
We use the router-outlet directive, an Angular 2 Routing directive that displays the active route (like ng-view ).
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With