我在我的{ provide: LocationStrategy, useClass: HashLocationStrategy },
使用app.module.ts
。但是,当我给this.route.url
它总是包含/
无论我在/home
或/dashboard
或/profile
我需要获得特定路径值
constructor(public router:Router) {} alert(this.router.url);
你route
实例应该从Router
constructor(
private router: Router
) { }
this.router.url // this must contains your full router path
不知道这是否适用于V5,但无论如何,可以帮助
您也可以订阅到路由器事件NavigationEnd,这似乎是永远得到当前地址的最佳方式。
重要笔记:
- 确保你把这个代码在contructor()
文件的app.component.ts
,为了总能获得最后的URL值。
// file: src/app/app-component
export class AppComponent {
constructor(private router: Router) {
// listen to events from Router
this.router.events.subscribe(event => {
if(event instanceof NavigationEnd) {
// event is an instance of NavigationEnd, get url!
const url = event.urlAfterRedirects;
console.log('url is', url);
}
})
}
}
如果你不希望散列是URL的一部分,让使用哈希虚假如下图所示的代码:
RouterModule.forRoot([
{path: 'welcome', component: WelcomeComponent},
{path: '', redirectTo: 'welcome', pathMatch: 'full'},
{path: '**', component: PageNotFoundComponent},
], {useHash: false}),
ProductModule,
我希望它能帮助