Angular 2 嵌套组件中的路由更改

Angular 2 Route changing in nested component

我有一个相当简单的 Angular 2 问题。我有一个主视图,顶部有一个工具栏,下面有一个路由器插座。

mainView.ts

@Component({
    selector: 'pod-app',
    template: `
        <pod-toolbar></pod-toolbar>

        <router-outlet></router-outlet> <!-- USE THIS router-outlet -->
    `,
    directives: [ ToolbarComponent, RouteComponent, ROUTER_DIRECTIVES ],
    providers: [
        EventService,
        ROUTER_PROVIDERS
    ]
})

@RouteConfig([
    {
        path: '/list',
        name: 'ListView',
        component: ListViewComponent,
        useAsDefault: true
    },
    {
        path: '/tileView',
        name: 'TileView',
        component: TileViewComponent
    },
    {
        path: '/pdfView',
        name: "PdfView",
        component: PdfViewComponent
    }
])

export class MainComponent implements OnInit { 
    ...blah...blah...blah
 }

然后我有我的toolbar.ts嵌套在里面是我的路线导航列表

toolbar.ts

@Component({
    selector: 'pod-toolbar',
    template: `
        <div class="demo-toolbar">
            <p>
                <md-toolbar color="primary">

                    <pod-routes></pod-routes> <!-- appRoutes.ts component -->

                </md-toolbar>
            </p>

        </div>
    `,
    directives: [MdToolbar, MdButton,RouteComponent, ROUTER_DIRECTIVES],
    providers: [ROUTER_PROVIDERS]
})

export class ToolbarComponent implements OnInit {
    ...blah...blah...blah
}

然后这是嵌套在工具栏内的路由链接,需要更改主视图中工具栏下方的视图

appRoutes.ts

@Component({
    selector: 'pod-routes',
    template: 
    `
        <nav>
            <a [routerLink]="['/ListView']"><img src="pathto.png" height="45" width="45"></a>
            <a [routerLink]="['/TileView']"><img src="pathto.png" height="40" width="45" ></a>
            <a [routerLink]="['/PdfView']"><img src="pathto.png" height="40" width="45" ></a>
        </nav>
    `,
    directives: [ROUTER_DIRECTIVES]
})

export class RouteComponent{

}

那么,我做错了什么?这是我希望它设置的方式,但如果这不可行,那么也许我可以将路由移动到工具栏中,如果那不可行,那么我可以将整个工具栏移动到 mainView 中,我不这样做我想做,但如果我必须做,我会做。

更新

从 appRoutes.ts 中删除了 ROUTER_PROVIDERS,仍然有同样的问题。

更新 2

根据答案的建议将“/”添加到 url 路由,同样的问题,地址栏中的 url 发生了变化,但工具栏下方的 ui 没有变化

更新 3

从 toolbar.ts 和 mainView.ts 文件中删除了 providers: [ROUTER_PROVIDERS] 并在 app.ts

中引导了 ROUTER_PROVIDERS
bootstrap(MainComponent, [ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy}) ] )
     .catch(err => console.error(err));

似乎成功了。非常感谢 Gunter 支持我并帮助我解决问题。他的 Plunker 真的帮了大忙!

更新2

Plunker example

更新

在路由名称前加上 / 以告知根路由器应导航到此路由:

<a [routerLink]="['/ListView']"><img src="pathto.png" height="45" width="45"></a>
<a [routerLink]="['/TileView']"><img src="pathto.png" height="40" width="45" ></a>
<a [routerLink]="['/PdfView']"><img src="pathto.png" height="40" width="45" ></a>

原创

不要多次提供 ROUTER_PROVIDERS

providers: [
    EventService,
    ROUTER_PROVIDERS
]

ROUTER_PROVIDERS 应该在根组件中只提供一次,而不是在其他任何地方(或者在 boostrap(...) 中)