Routing in Angular2 - Link “['Name']” does not resolve to a terminal instruction

放肆的年华 提交于 2019-11-30 11:17:54
Eric Martinez

This may be useful for other users, so I'm writing it as an aswer, the comment may be too short.

In your RouteConfig you defined ChildItem to be a parent route. The /... part makes it to be a parent route, which means it has children.

@RouteConfig([
        // This route is a parent route
        { path: '/child/...', component: ChildItem, as: 'ChildItem' }
])

So you can't simply route to ['ChildItem'] without specifying a child route or without adding useAsDefault: true in the route.

So you have two options :

  • Option 1 : Add useAsDefault: true in one of your child routes
@RouteConfig([
        { path: '/1', component: SubItem1, as: 'SubItem1', useAsDefault: true},
        { path: '/2/', component: SubItem2, as: 'SubItem2' },
        { path: '/3/', component: SubItem3, as: 'SubItem3' }
])
export class ChildItem{}

With this option, everytime you navigate to ChildItem it will redirect you immediatly to SubItem1. Note : as was deprecated alphas ago, stick to name.

  • Option 2 : Specify a child in the link (you can do this in two ways)
// First way
<a [routerLink]="['/ChildItem', 'SubItem1']">Click Me</a>

// Second way
<a [routerLink]="['/ChildItem/SubItem1']">Click Me</a>

Both ways are similar, but the first one will let you to pass parameters to each route, for example :

// ChildItem gets "id"
// SubItem1 gets "itemName"
<a [routerLink]="['/ChildItem', {id: 'someId'}, 'SubItem1', {itemName: 'someName'}]">Click Me</a>

// Only SubItem1 gets "id"
<a [routerLink]="['/ChildItem/SubItem1', {id: 'someId'}]">Click Me</a>

I hope this was helpful and clear.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!