Reputation: 371
In my app.component.ts I have the code below to get the route name, but I always get /
. Does anyone know why? I expect to get for example home
, contact
.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
constructor(private router: Router) {
console.log(router.url);
}
}
Upvotes: 3
Views: 2978
Reputation: 322
If you want to get the before initialized route you need to do the following.
constructor( private route: ActivatedRoute, private router: Router, private url: LocationStrategy ) {}
ngOnInit(): void {
this.router.events.subscribe((event) => {
console.log(event); // If you see the log here, You can get lot of events. So based on your requirement you can able to filter
if (event instanceof NavigationStart) {
console.log((event as NavigationStart).url);
}
});
}
Upvotes: 0
Reputation: 60528
The AppComponent is only initialized, and your constructor executed, when the application is loaded. Hence the reason it shows "/". As you navigate to other routes, the AppComponent remains loaded and the constructor is not executed again.
If you could provide more information on what you are trying to accomplish, we may be able to provide an alternative suggestion for you.
If you want to watch the routes and obtain the URL, you can use an observable here instead. Something like this:
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
console.log((<NavigationEnd>event).url);
}
});
Or if you just want it for debugging purposes, you can enable tracing like so:
RouterModule.forRoot([
{ path: 'welcome', component: WelcomeComponent },
{ path: '', redirectTo: 'welcome', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
], { enableTracing: true })
Upvotes: 11