Angular2是否有办法从路由器中获取路由列表? [英] Angular2 is there a way to get a list of routes out of the Router?
问题描述
我想做的是通过迭代Angular2中配置的路由列表来动态构建导航。我似乎在路由器中找不到可以访问已配置路由的任何地方。有人尝试过这样的事情吗?
What I would like to do is dynamically build my navigation by iterating through a list of configured routes in Angular2. I cannot seem to find anywhere in the Router where I can access the configured routes. Has anyone tried anything like this?
我查看了路由器
的注册表
属性,但似乎没有任何可用。
I looked into the Router
's registry
property but it doesn't seem to have anything usable.
@Component({
selector: 'my-app'
})
@View({
directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES],
template: `
<h1>Routing Example</h1>
<div>
<div>
<b>Main menu: </b>
<a [router-link]="['Home']">Home</a> |
<a [router-link]="['One']">One</a> |
<a [router-link]="['Two']">Two</a>
<!--
// I would rather do something like this:
<a *ng-for="#route of router.routes" [router-link]="['route.name']">{{ route.name }}</a>
-->
</div>
<div>
<router-outlet></router-outlet>
</div>
</div>
`
})
@RouteConfig([
{ path: '/', redirectTo: '/home' },
{ path: '/home', as: 'Home', component: Main },
{ path: '/one', as: 'One', component: One },
{ path: '/two', as: 'Two', component: Two },
])
export class MyApp {
constructor(public location: Location, public router: Router){
}
}
推荐答案
我还需要动态生成链接。据我了解,问题在于路由器没有其他方法可以生成链接,而只能手动将它们放在 [router-link]
中。但是... 但他们计划添加它们。有很多功能排在路由器的队列中,希望他们能尽快添加它们(;
I also needed to dynamically generate links. As I understand it, problem is that router doesn't have methods to generate links other then manually putting them in [router-link]
. Yet... but they plan to add them. There's lot of features in queue for the router, hopefully they add them soon (;
对于现在,我完成了这项工作-我将routerConfig放在了装饰器的外面,因此可以在此组件中使用它(如果导出,也可以在其他组件中使用):
For now I made this work - I put routerConfig outside the decorator, so I can use it in this component (and possibly others if I export it):
let routeConfig = [
{ path: '/', name: 'Intro', component: IntroRouteComponent, useAsDefault: true },
...
{ path: '/projects', name: 'Projects', component: ProjectsRouteComponent },
{ path: '/about', name: 'About', component: AboutRouteComponent },
];
@Component({
directives: [ROUTER_DIRECTIVES],
providers: [],
selector: 'app',
template: `
<a (click)="back()" *ngIf="prevRoute">{{ prevRoute }}</a>
<a (click)="forward()" *ngIf="nextRoute">{{ nextRoute }}</a>
`,
})
@RouteConfig(routeConfig)
export class AppComponent {
private nextRoute: any;
private prevRoute: any;
constructor(private _router: Router) {
this._router.subscribe(route => {
let i = routeConfig.findIndex(r => r.path === ('/' + route));
this.prevRoute = routeConfig[i - 1] ? routeConfig[i - 1].name : false;
this.nextRoute = routeConfig[i + 1] ? routeConfig[i + 1].name : false;
});
}
back() {
this._router.navigate(Array(this.prevRoute));
}
forward(): any {
this._router.navigate(Array(this.nextRoute));
}
}
这篇关于Angular2是否有办法从路由器中获取路由列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!