3

I am unable to get the URL nor the path from ActivatedRoute nor Router imports. It outputs a blank for path "" and '/' for URL. I remember using a working version. The only thing that captures the right route the Router.events. I am also unable to subscribe to the URL in the ActivatedRoute. Here is the code

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router, ActivatedRoute, UrlSegment, NavigationStart, RoutesRecognized } from '@angular/router';

@Component({
  selector: 'api-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  routePath: string = '';

  constructor(
    private _r: Router,
    private _ar: ActivatedRoute) {
    this._r.events.subscribe((event: any) => {
      if (event instanceof RoutesRecognized) {
          // '/teams' output with route http://localhost:4200/teams
        console.log(event.url);
      }
      // NavigationStart // NavigationEnd // NavigationCancel // NavigationError // RoutesRecognized
    });

  }


  ngOnInit() {
    console.log(this._ar.pathFromRoot.toString()); // Blank output with route http://localhost:4200/teams
    console.log(this._ar.routeConfig.path.toString());  // Blank output with route http://localhost:4200/teams
    console.log(this._ar.snapshot.url);  // Blank output with route http://localhost:4200/teams
    this._ar.url.subscribe((urlsegment: UrlSegment[]) =>{
      console.log(urlsegment) // Unable to subscribe with route change to /teams
    })
  }

}

Anything I am missing here? I have seen this Angular router url returns slash

My routes:

const APPMainRoutes: Routes = [
    {path: '', redirectTo: '/login', pathMatch: 'full'},
    {path: 'teams', component: CollaborateComponent},
    {path: 'login', component: LoginComponent},
];

My ng versions:

Angular CLI: 6.1.4 Node: 10.7.0 OS: linux x64 Angular: 6.1.4 ... animations, cli, common, compiler, compiler-cli, core, forms ... http, language-service, platform-browser ... platform-browser-dynamic, router

Package Version

@angular-devkit/architect 0.7.4 @angular-devkit/build-angular 0.7.4 @angular-devkit/build-optimizer 0.7.4 @angular-devkit/build-webpack 0.7.4 @angular-devkit/core 0.7.4 @angular-devkit/schematics 0.7.4 @angular/cdk 6.4.6 @angular/material 6.4.6 @ngtools/webpack 6.1.4 @schematics/angular 0.7.4 @schematics/update 0.7.4 rxjs 6.2.2 typescript 2.7.2 webpack 4.9.2

Gary
  • 2,293
  • 2
  • 25
  • 47
  • As i can see, You have not use DashboardComponent inside your Routes. and remove slash from "redirectTo: '/login'" – Aniket Avhad Sep 03 '18 at 05:14
  • It did not help. It might not help as well. My issue is with `/teams` route not getting captured as `/` or path as `""` I would have worried if it was only with `/login` – Gary Sep 03 '18 at 05:17
  • Seems it works only with events capture withing constructor - if you noticed – Gary Sep 03 '18 at 05:18
  • 1
    https://stackblitz.com/edit/angular-mv9wy7?file=src%2Fapp%2Fapp.module.ts see this demo.. here i am able to get url using Router – Aniket Avhad Sep 03 '18 at 05:24
  • Aniket, Check the result in app.component in this demo. https://stackblitz.com/edit/angular-taiifx?file=src%2Fapp%2Fapp.component.ts – Gary Sep 03 '18 at 05:36
  • Aniket, the problem is I am also not able to subscribe the url change from app.component – Gary Sep 03 '18 at 05:39

4 Answers4

1

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
Jihoon Kwon
  • 745
  • 5
  • 14
  • Sorry didnt work - neither. Getting a '/' and map is empty – Gary Sep 03 '18 at 05:08
  • @Gary please check your url setting in Routes module. if you access http://localhost/test , then this._r.url have to return /test. – Jihoon Kwon Sep 03 '18 at 05:34
  • 1
    @what is url for DashboardComponent ?? – Jihoon Kwon Sep 03 '18 at 05:35
  • Good catch - Its the sidebar. and is the parent dom for router-outlet. The route components can catch the url. – Gary Sep 03 '18 at 05:37
  • Can you check the link here https://stackblitz.com/edit/angular-taiifx?file=src%2Fapp%2Fapp.component.ts – Gary Sep 03 '18 at 05:38
  • 1
    @Gary check https://stackblitz.com/edit/angular-s9mute?file=src/app/login/login.component.ts If you need to get url /login /team , then you should define LoginComponent or TeamComponent. And if you want to get the url link in the parent component, you have to use another way... – Jihoon Kwon Sep 03 '18 at 05:51
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179294/discussion-between-gary-and-jihoon-kwon). – Gary Sep 03 '18 at 05:52
1

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

Aniket Avhad
  • 4,025
  • 2
  • 23
  • 29
1

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
    });

}
Gary
  • 2,293
  • 2
  • 25
  • 47
  • thx a lot ! it helped me get the URL the user typed in his browser on boostrapped app component on init (I was trying to get the 'landing page' the user intended to go before anything is actually rendered) – yactouat Jul 27 '20 at 20:29
1

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

danday74
  • 52,471
  • 49
  • 232
  • 283