如何在我的Angular2应用程序中@Routes中列出/输出所有路由 [英] How to list / output all routes in @Routes in my Angular2 App
问题描述
我有一个简短的问题.我目前正在通过 https://angular.io/docs/ts/latest/api/router/Router-class.html ,但我想知道,在Angular2的main.ts
中,我的路由定义如下:
I have a quick question. I'm currently looking through https://angular.io/docs/ts/latest/api/router/Router-class.html but I was wondering, in my Angular2's main.ts
I have my routes defined thus:
@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 },
])
现在在其他位置的组件中,我导入Router类.在我的组件(或组件模板)中,我想遍历所有定义的路由,或者只是能够访问它们.有内置的方法可以做到这一点吗?像一些返回对象数组的函数一样?这是我想要的一个粗略想法...
Now in a component elsewhere I import the Router class. In my component (or the component template) I would like to loop through all my routes defined or just be able to access them. Is there a built in way to do this? Like some function that returns an object array? Here is a crude idea of what I want...
@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); ????
}
}
推荐答案
以下是更好的版本,它将列出所有可能的路线(根据评论进行了固定):
Here is a better version which will list all possible routes (fixed according to comments):
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++) {
const route = config[i];
console.log(parent + '/' + route.path);
if (route.children) {
const currentPath = route.path ? parent + '/' + route.path : parent;
this.printpath(currentPath, route.children);
}
}
}
这篇关于如何在我的Angular2应用程序中@Routes中列出/输出所有路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!