Unable to get the path nor url from angular router

泄露秘密 提交于 2019-12-06 07:27:36

You can get url info like this :

ngOnInit() {
    console.log(this._r.url);
  }

And if you need to get queryParams in the url You can get :

this._r.snapshot.queryParamMap

You can check instanceof NavigationStart and NavigationEnd

here's is the example

in app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';

export class AppComponent {

  constructor(private router: Router) { }

  ngOnInit() {

    this.router.events.subscribe((event: any) => {
      if(event instanceof NavigationStart) {
        console.log('start => ',event.url);
      }
      if(event instanceof NavigationEnd) {
        console.log('end => ',event.url);
      }
    });
  }
}

Stackblitz demo

The component where I was trying to access the url or the path was the host/parent/parallel component to the component tree. All the above failures allowed capture of right path inside the route components but not the parent/host/paralleltree component. Only Router.events work there. Surprisingly I was unable to capture and make work the ActivatedRoute.url.subscribe as well inside the parent/host.

<app-cmp>
Router and ActivatedRoute does not Work here. Only Router.events Work here
<router-outlet>
<team-cmp>Router and ActivatedRoute Works here</team-cmp>
</router-outlet>
<sidebar-cmp>
Router and ActivatedRoute does not Work here. Only Router.events Work here
<sidebar-cmp>
</app-cmp>

This works in host/parent/parallel tree - or :

// inject in constructor
constructor( private _router: Router) {

// Call below anywhere within Init or Constructor etc
this._router.events.subscribe((event: any) => {
      if (event instanceof RoutesRecognized) {
        console.log(event.url); // WORKS
      }
      // NavigationStart // NavigationEnd // NavigationCancel // NavigationError // RoutesRecognized
    });

}

If all else fails you can use location.pathname which is global

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!