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

前端 未结 1 508
予麋鹿
予麋鹿 2021-01-01 17:59

I am trying to get a simple app working with child routing.

When I setup the routes on my child component I get the following error message:

Link \"[         


        
相关标签:
1条回答
  • 2021-01-01 18:34

    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.

    0 讨论(0)
提交回复
热议问题