Angular router url returns slash

北城以北 提交于 2019-12-05 03:47:05

Instead of trying to use Router (which is not ready to give you final route at this moment of navigation lifecycle), you can use Location service (https://angular.io/api/common/Location) and its method path, which will give you the url without base href. On the contrary, window.location.pathname is not aware of your angular toys and will give you path including base href.

import { Location } from '@angular/common';

export class AppComponent implements OnInit {
  constructor(private location: Location) {}

  ngOnInit(){
    console.log(this.location.path());
  }

}

I have the same issue. The router.url returns a slash because when ngOnInit runs on the main app component, the route is the root. I got the correct value for the url by doing this.

  this.router.events
  .pipe(
    filter(e => e instanceof NavigationEnd)
  )
  .subscribe( (navEnd:NavigationEnd) => {
    console.log(navEnd.urlAfterRedirects);
  });

Hope that helps. This did not work with Angular Universal however... still trying to figure that out.

Type 1.We can also use window.location.pathname

Type 2.constructor(router: Router) { 

      router.events.subscribe((url:any) => console.log(url));

      console.log(router.url);  // to print only path eg:"/login"
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!