将类型安全的路线数据传递给角度为 2 的路线 [英] Passing type-safe route data to routes in angular 2

查看:17
本文介绍了将类型安全的路线数据传递给角度为 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);

为了使数据类型安全,我创建了一个 RouteData 类,该类将保存 ShowTopBarShowSideBar 值并通过一个构造函数.

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;
}

现在,我以下列方式更改了 Routes 的声明:

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)}

];

编译时出现以下错误:

静态解析符号值时遇到错误.调用函数'RouteData',不支持函数调用.考虑更换带有对导出函数的引用的函数或 la mbda,解析符号 AppRoutingModule

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

我的问题是我们如何以类型安全的方式将 RouteData 传递给路由,以便我可以利用类型安全.

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

推荐答案

你可以在下面做,

@angular/router 扩展 Route 并更新如下数据类型,

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;
}

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,

这篇关于将类型安全的路线数据传递给角度为 2 的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆