在angular2中添加属性到路由

时间:2016-03-09 10:29:43

标签: angular angular2-routing

我想知道是否可以在RouteConfig装饰器中定义的路由中添加自定义属性。

我想添加路由需要身份验证的内容:

@RouteConfig([
  {
    path: "/login",
    name: "Login",
    component: LoginComponent,
    authenticate: false,
  },
  {
    path: "/home",
    name: "Home",
    component: HomeComponent,
    authenticate: true
  }
])

如果可以,我如何在组件中获得值“authenticate”?

1 个答案:

答案 0 :(得分:3)

我认为您可以利用data界面的RouteDefinition属性:

@RouteConfig([
  {
    path: "/login",
    name: "Login",
    component: LoginComponent,
    data: {
      authenticate: false
    }
  },
  {
    path: "/home",
    name: "Home",
    component: HomeComponent,
    data: {
      authenticate: true
    }
  }
])

类型为any,因此您可以将所需内容放入其中(请参阅https://github.com/angular/angular/blob/master/modules/angular2/src/router/route_definition.ts#L25):

export interface RouteDefinition {
  path?: string;
  aux?: string;
  component?: Type | ComponentDefinition;
  loader?: Function;
  redirectTo?: any[];
  as?: string;
  name?: string;
  data?: any;
  useAsDefault?: boolean;
}