Angular 2中的嵌套路由,具有发布候选组件路由器



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

对于顶部的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>

我希望这个布局能让我有URL,比如:

/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 route param不直接属于CustomerComponent,而是属于AppComponent中的Routes。

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

我读到过这样一种方法,即使用一个类似于"当前用户"变量的服务来共享状态数据,并将其注入子路由中的所有组件中。

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

有什么方法可以让我从路线中得到名字吗?或者有更好的方法吗?

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

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

其中配置文件是组件中的属性

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

最新更新