【问题标题】:Nested Routes in Angular 2 with release candidate Component RouterAngular 2 中的嵌套路由和候选发布组件路由器
【发布时间】:2016-09-14 02:42:22
【问题描述】:

我正在构建一个简单的应用程序,其中有人可以通过电子邮件在表单中搜索用户,然后查看与该用户相关的各种数据。

对于顶级 AppComponent 组件,我有以下路线:

@Routes([
  {path: '/:name',  component: CustomerComponent},
  {path: '/search',  component: SearchComponent}
])

搜索路径对应于搜索客户的表单,/:name 路径旨在显示该客户的数据。

我的想法是让客户组件有一些基本布局,可能还有用户个人资料图片之类的东西,然后有指向客户个人资料不同部分的链接,如下所示:

@Routes([
  {path: '/profile',  component: CustomerProfileComponent},
  {path: '/loyalty',  component: CustomerLoyaltyComponent},
  {path: '/coupons',  component: CustomerCouponsComponent},
  {path: '/settings',  component: CustomerSettingsComponent}
])

和html:

<div>
    <span>
        <a [routerLink]="['./profile']">Profile</a>
        <a [routerLink]="['./loyalty']">Loyalty</a>
        <a [routerLink]="['./coupons']">Coupons</a>
        <a [routerLink]="['./settings']">Settings</a>
    </span>
</div>
<div>
    <router-outlet></router-outlet>
</div>

我希望这种布局能让我拥有如下网址:

/search
/joe/profile
/joe/loyalty
/joe/coupons
/joe/coupons/14/
/joe/coupons/14/edit
...etc

我遇到的问题是,在子路由器中,我似乎无法使用 RouteSegment 来获取用户的电子邮件。例如,在 CustomerProfileComponent 中,我实现了 OnActivate 并尝试以下操作:

routerOnActivate(curr: RouteSegment) {
    let name = curr.getParam('name');
    console.log("profile says " + name);
}

但是,这会打印“配置文件说未定义”。我想这是因为 :name 路由参数不直接属于 CustomerComponent,而是属于 AppComponent 中的路由。

我希望能够从每个视图的 RouteSegment 中获取名称,然后能够使用它来访问一些 api 以获取有关该用户的特定数据。

我已经读过,一种方法是通过拥有类似“当前用户”变量的东西来共享状态数据的服务,并将服务注入到子路由中的所有组件中。

但是,我认为如果我不需要以这种方式在组件之间共享状态,它会使应用程序更简单。

有什么方法可以从路线中获取名称,或者有更好的方法吗?

【问题讨论】:

  • 嗨,你能在你的代码中发布一个 plunker 吗?关于 angular2 路由器的文档不多,您似乎已经弄清楚了

标签: angular angular2-routing


【解决方案1】:

您需要在routeLink中添加如下信息

<a [routerLink]="['./profile', profile.name ]">Profile</a>

其中 profile 是组件中的属性

此外,可用的 URL 将是 /profile/joelayout/joe

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 2016-09-09
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多