如何在我的Angular 2应用程序中列出/输出@路由中的所有路由?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (5)
  • 关注 (0)
  • 查看 (165)

main.ts我的路线是这样界定的:

@Routes([
    { path: '/', component: HomeComponent },
    { path: '/about-me', component: AboutMeComponent },
    { path: '/food', component: FoodComponent },
    { path: '/photos', component: PhotosComponent },
    { path: '/technology', component: TechnologyComponent },
    { path: '/blog', component:Blogomponent },
])

现在,在其他组件中,我导入了路由器类。在我的组件(或组件模板)中,我希望遍历我定义的所有路由,或者只访问它们。有没有建好的方法来做这件事?就像某个返回对象数组的函数一样?这是我想要的一个粗略的想法..。

@Component({
    selector: 'ms-navigation',
    templateUrl: 'src/navigation/navigation.template.html',
    directives: [ ROUTER_DIRECTIVES ]
})

export class NavigationComponent {
    constructor(private router:Router) {   
        // what can I do here to get an array of all my routes?
        console.log(router.routes); ????
    }
}
提问于
用户回答回答于

将路由分配到如下所示的常量

const appRoutes: Routes = [
    {
        path: 'asd',
        component: asdComponent
    },
    {
        path: 'ar',
        component: arComponent
    }
];

export const routing = RouterModule.forRoot(appRoutes);

导入Const路由

import { routing }        from './app.routing';
export class AppComponent {
   route=routing;
   /// route.providers is an array which internally contains the list of routes provided
   console.log(route.providers);
}
用户回答回答于
  import { Router, Route } from "@angular/router";
  constructor(private router: Router) {

  }
  ngOnInit() {
    this.printpath('', this.router.config);
  }
  printpath(parent: String, config: Route[]) {
    for (let i = 0; i < config.length; i++) {
      let r = config[i];
      console.log(parent + '/' + r.path);
      if (r.children && r.path) {
        this.printpath(parent + '/' + r.path, r.children);
      }
    }
  }
用户回答回答于
constructor(private router: Router) {}

ngOnInit() {
  console.log('configured routes: ', this.router.config);
}
用户回答回答于

对于@RangeVersion 2.00,我通过routeConfig属性找到了一个子程序列表。

这里是我的组件的一个例子。注意,我是通过‘父’属性访问子的,因为这个组件实际上是一个子组件,因为我在子路由器出口中呈现它。

import { Component } from '@angular/core';
import {Route, ActivatedRoute, Router} from "@angular/router";

@Component({
    selector: 'list',
    template: require('./list.component.html')
})
export class ListComponent {
    children = new Array<RouteLink>();

    constructor(private router: Router, private activatedRoute: ActivatedRoute) {
        for (let child of activatedRoute.parent.routeConfig.children) {
            if (child.path && child.data["breadcrumb"]) {
                this.children.push(new RouteLink(child.path, child.data["breadcrumb"]));
            }
        }
    }
}

export class RouteLink {
    constructor(private path: string, private name: string) {  }
}
用户回答回答于

如果只需要将路由路径作为字符串使用,则可以通过遍历Router对象的config阵列。

    for (var i = 0; i < this.router.config.length; i++) {
        var routePath:string = this.router.config[i].path;
        console.log(routePath);
    }

扫码关注云+社区

领取腾讯云代金券