Angular2 is there a way to get a list of routes out of the Router?

喜夏-厌秋 提交于 2019-12-05 01:22:39

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 (;

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

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!