【问题标题】:Angular2 is there a way to get a list of routes out of the Router?Angular2有没有办法从路由器中获取路由列表?
【发布时间】:2016-03-09 21:05:01
【问题描述】:

我想做的是通过遍历 Angular2 中配置的路由列表来动态构建我的导航。我似乎在路由器中找不到可以访问配置路由的任何地方。有人试过这样的吗?

我查看了Routerregistry 属性,但它似乎没有任何可用的东西。

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

【问题讨论】:

    标签: routing angular


    【解决方案1】:

    我还需要动态生成链接。据我了解,问题是路由器没有生成链接的方法,然后手动将它们放入[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));
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-16
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-07-07
      相关资源
      最近更新 更多