typescript - Ako zobraziť/vypísať všetky trasy v @Routes v mojej aplikácii Angular2
Mám rýchlu otázku. Momentálne prezerám https://angular.io/docs/ts/latest/api/router/Router-class.html, ale zaujímalo by ma, v mojom Angular2 main.ts mám svoje trasy definované takto:
@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 },
])
Teraz v inom komponente importujem triedu Router. V mojom komponente (alebo v šablóne komponentu) by som chcel prechádzať všetkými mojimi definovanými trasami alebo sa k nim len vedieť dostať. Existuje na to zabudovaný spôsob? Ako nejaká funkcia, ktorá vráti pole objektov? Tu je hrubý nápad toho, čo chcem...
@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); ????
}
}
Odpoveď č. 1
Aktualizácia júl 2024: Keďže táto odpoveď je už dávno, nezachytil som všetky novšie verzie, existuje doplnok k tejto odpovedi od Adriana pre novšie verzie s odloženým načítavaním. Pre novšie verzie Angularu sa, prosím, odvolajte aj na to.
Tu je lepšia verzia, ktorá bude zoznamovať všetky možné trasy (opravené podľa komentárov):
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);
}
}
}
Odpoveď č. 2
Zjavne existuje veľmi kompaktný spôsob, ako to urobiť:
constructor(private router: Router) {}
ngOnInit() {
console.log('configured routes: ', this.router.config);
}
Odpoveď č. 3
Ak potrebujete iba cesty trás ako reťazce, môžete ich nájsť iterovaním cez pole config vášho objektu Router.
for (var i = 0; i < this.router.config.length; i++) {
var routePath:string = this.router.config[i].path;
console.log(routePath);
}
Odpoveď č. 4
Používam túto komponentu na získanie všetkých rout v 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)
}
}
Aktualizujte Angular 14: configLoader.load
(<any>this._router).configLoader.loadChildrenAktualizovať Angular 17: configLoader.loadChildren
(<any>this._router).navigationTransitions.configLoader.loadChildren