4

In Angular 2 I want to be able to use route.path to.. get the path.

Inside a components constructor I have:

constructor(private route: Route) {}

So I would like to be able to call:

this.route.path

And for the app bootstrap I got:

bootstrap(AppComponent,
[
    ROUTER_PROVIDERS,
]);

But I still get the No Provider for Route! error

RobSeg
  • 985
  • 4
  • 14
  • 37
  • If using outside the constructor just try once changing modifier in contructor to public – mayur May 06 '16 at 08:42

3 Answers3

4

I assume what you to inject Location instead of Route. Route is for route configuration and there is no way for Angular to know which Route instance to inject.

Location provides the path() function to get the current URL.

Depending on the Angular2 version there are different paths where to import it from.

See also Location and HashLocationStrategy stopped working in beta.16

<= beta 15

import {Location} from 'angular2/router';

>= beta 16 < rc.0

import {Location} from 'angular2/platform/common';  
constructor(private location:Location) {
  console.log(location.path());
}

>= rc.0

import {Location} from '@angular/common';
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

The Route class can be injected. You can inject the Router one or RouteParams:

constructor(private router:Router,private params:RouteParams) {
  this.id = params.get('id');
}

If you need the path of the current route, inject rather the Location class and use its path method

constructor(private location:Location) {
  var path = location.path();
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • From where do you import RouteParams post beta (rc.1). It doesn't work to import it from @angular/router and I can't find where it says this anywhere yet. – mottosson May 06 '16 at 10:29
0

Try with ROUTER_BINDINGS instead.

Pierre Urban
  • 149
  • 4