如何从 app.component 获取路线名称?
How can I get route name from app.component?
在我的 app.component.ts 中,我有下面的代码来获取路线名称,但我总是得到 /
。有谁知道为什么?我希望得到例如 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);
}
}
AppComponent 仅在加载应用程序时初始化,并执行您的构造函数。因此它显示“/”的原因。当您导航到其他路由时,AppComponent 保持加载状态并且不会再次执行构造函数。
如果您可以提供更多关于您要完成的目标的信息,我们或许可以为您提供替代建议。
如果你想观察路线并获得URL,你可以在这里使用一个observable。像这样:
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
console.log((<NavigationEnd>event).url);
}
});
或者如果您只是想将其用于调试目的,您可以像这样启用跟踪:
RouterModule.forRoot([
{ path: 'welcome', component: WelcomeComponent },
{ path: '', redirectTo: 'welcome', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
], { enableTracing: true })
如果你想获取初始化前的路由,你需要做以下操作。
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);
}
});
}
在我的 app.component.ts 中,我有下面的代码来获取路线名称,但我总是得到 /
。有谁知道为什么?我希望得到例如 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);
}
}
AppComponent 仅在加载应用程序时初始化,并执行您的构造函数。因此它显示“/”的原因。当您导航到其他路由时,AppComponent 保持加载状态并且不会再次执行构造函数。
如果您可以提供更多关于您要完成的目标的信息,我们或许可以为您提供替代建议。
如果你想观察路线并获得URL,你可以在这里使用一个observable。像这样:
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
console.log((<NavigationEnd>event).url);
}
});
或者如果您只是想将其用于调试目的,您可以像这样启用跟踪:
RouterModule.forRoot([
{ path: 'welcome', component: WelcomeComponent },
{ path: '', redirectTo: 'welcome', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
], { enableTracing: true })
如果你想获取初始化前的路由,你需要做以下操作。
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);
}
});
}