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 }, ])
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); ???? } }
Routing is a process of changing the state of your Application by loading different components depending upon the URL that the user enters. Angular 2 parses the entered URL by the user and try to identify the routes according the different segments of URL.
Routing for the Angular app is configured as an array of Routes , each component is mapped to a path so the Angular Router knows which component to display based on the URL in the browser address bar. The Routes array is passed to the RouterModule.
Show activity on this post. You can check the current route by injecting the Location object into your controller and checking the path() , like so: class MyController { constructor(private location:Location) {} ...
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); } } }
Apparently there is a very compact way to do it:
constructor(private router: Router) {} ngOnInit() { console.log('configured routes: ', this.router.config); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With