问题
What I would like to do is dynamically build my navigation by iterating through a list of configured routes in Angular2. I cannot seem to find anywhere in the Router where I can access the configured routes. Has anyone tried anything like this?
I looked into the Router
's registry
property but it doesn't seem to have anything usable.
@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){
}
}
回答1:
I also needed to dynamically generate links. As I understand it, problem is that router doesn't have methods to generate links other then manually putting them in [router-link]
. Yet... but they plan to add them. There's lot of features in queue for the router, hopefully they add them soon (;
For now I made this work - I put routerConfig outside the decorator, so I can use it in this component (and possibly others if I export it):
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));
}
}
来源:https://stackoverflow.com/questions/34096685/angular2-is-there-a-way-to-get-a-list-of-routes-out-of-the-router