我有一个简短的问题。我目前正在通过https://angular.io/docs/ts/latest/api/router/Router-class.html查找,但我想知道,在我的Angular2的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 },
])
现在,在别处的一个组件中,我导入了Router类。在我的组件(或组件模板)中,我希望遍历我定义的所有路由,或者只是能够访问它们。有没有一种内置的方法可以做到这一点?像一些返回对象数组的函数?这是我想要的粗略想法。
@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); ????
}
}
发布于 2017-09-11 15:30:02
显然,有一种非常简洁的方法:
constructor(private router: Router) {}
ngOnInit() {
console.log('configured routes: ', this.router.config);
}
发布于 2016-11-24 02:28:15
如果只需要字符串形式的路由路径,可以通过迭代Router
对象的config
数组来找到它们。
for (var i = 0; i < this.router.config.length; i++) {
var routePath:string = this.router.config[i].path;
console.log(routePath);
}
发布于 2021-02-11 19:45:35
我正在使用这个公司。获取angular 9中的所有路由
import { Compiler, Component, Injector, OnInit } from '@angular/core';
import { Route, Router } from '@angular/router';
@Component({
templateUrl: './sitemap.component.html'
})
export class SiteMapComponent implements OnInit {
public urls: string[] = [];
constructor(private _router: Router, private compiler: Compiler, private injector: Injector) {
}
ngOnInit() {
this._router.config.forEach(i => {
this.getPaths(i);
})
}
getPaths(route: Route, parent: string = '') {
if (route.redirectTo) {
return;
}
if (route.children) {
route.children.forEach(i => {
this.getPaths(i, parent + route.path);
});
}
else if (route.loadChildren) {
(<any>this._router).configLoader.load(this.injector, route).subscribe(i => {
i.routes.forEach(j => {
this.getPaths(j, parent + route.path)
});
});
}
else if (route.path != null) {
this.setPath(route.path, parent);
}
}
setPath(path, parent) {
let fullPath: string;
if (path != null) {
if (parent) {
fullPath = `/${parent}/${path}`;
}
else {
fullPath = `/${path}`
}
}
this.urls.push(fullPath)
}
}
https://stackoverflow.com/questions/37569936
复制相似问题