asHkER
asHkER

Reputation: 435

Angular 2 - Can't get url from router

I can't get the url when I use console.log(_router.url). It only returns a / (slash)

When I do the below code:

constructor(
    private el: ElementRef,
    private _auth:AuthenticationService,
    @Inject(AppStore) private store: Store<AppState>,
    private _router:Router,
  ) {

    console.log(_router);
    console.log(_router.url);
  }

This is the result of console.log(_router) enter image description here

when (...) is clicked it displays "/languages"

enter image description here

but when I console.log(_router.url) this is only it prints

enter image description here

Upvotes: 4

Views: 1704

Answers (2)

Stas Sorokin
Stas Sorokin

Reputation: 3741

@Owain van Brakel's answer is correct but missing some details, I couldn't use this.router.url(as suggested in other answers in StackOverflow) so I used location.path(), the outcome is similar.

This is my code:

// This is important because when you use Location in the constructor it
// gets accepted but the wrong library is used. 
import { Location } from '@angular/common';

export class MainComponent {
   constructor(public location: Location) {
      console.log(this.location.path());
   }
}

Upvotes: 2

Owain van Brakel
Owain van Brakel

Reputation: 3349

You can always try to get the route from the location service

constructor(location: Location) {
  console.log(location.path());
}

Location docs

Upvotes: 2

Related Questions