如何获得在角5当前路由

问题描述 投票:4回答:3

我在我的{ provide: LocationStrategy, useClass: HashLocationStrategy },使用app.module.ts。但是,当我给this.route.url它总是包含/无论我在/home/dashboard/profile

我需要获得特定路径值

constructor(public router:Router) {} alert(this.router.url);

angular typescript angular-routing
3个回答
6
投票

route实例应该从Router

constructor(
    private router: Router
  ) { }

this.router.url // this must contains your full router path

5
投票

不知道这是否适用于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);
      }
    })

  }
}

0
投票

如果你不希望散列是URL的一部分,让使用哈希虚假如下图所示的代码:

  RouterModule.forRoot([
  {path: 'welcome', component: WelcomeComponent},
  {path: '', redirectTo: 'welcome', pathMatch: 'full'},
  {path: '**', component: PageNotFoundComponent},
], {useHash: false}),
ProductModule,

我希望它能帮助

© www.soinside.com 2019 - 2024. All rights reserved.