路由 – Angular2有没有办法从路由器中获取路由列表?

我想要做的是通过迭代Angular2中已配置路由的列表来动态构建我的导航.我似乎无法在路由器中找到可以访问已配置路由的任何位置.有没有人尝试过这样的事情?

我查看了Router的注册表属性,但似乎没有任何可用的东西.

@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));
  }

}

转载注明原文:路由 – Angular2有没有办法从路由器中获取路由列表? - 代码日志