我想做的是通过遍历 Angular2 中配置的路由列表来动态构建我的导航。我似乎无法在路由器中找到可以访问配置路由的任何地方。有没有人试过这样的事情?
我查看了 Router
的 registry
属性,但它似乎没有任何可用的内容。
@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]
。然而... but they plan to add them .有 lot of features在路由器队列中,希望他们尽快添加它们(;
现在我做了这个工作——我把 routerConfig 放在装饰器外面,所以我可以在这个组件中使用它(如果我导出它,可能还有其他组件):
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));
}
}
关于routing - Angular2 有没有办法从路由器中获取路由列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34096685/