Angular2 router undefined

I want to use the Router to retrieve the current URL(router) being displayed. To achieve this, I import the Router.

 import {RouteParams,Router} from 'angular2/router';

Next, I add it to the constructor of my component.

   constructor(public router : Router)

Now, whenever I try to call anything on it, I get errors, because ‘router’ remains undefined.

I read that there is another way of getting the URL by using ‘location’, but that this is not the recommended way. If however, Router is not the correct way of achieving this, I’m open for any suggestions. But I’d preferably find out why Router is undefined in this case.

The ROUTER_PROVIDERS have been specified like this:

bootstrap(AppComponent, [
    ROUTER_PROVIDERS, HTTP_PROVIDERS,....])

4
Leave a Reply

avatar
4 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Your index.html should contain

<script src="https://code.angularjs.org/2.0.0-beta.14/router.dev.js"></script>

AFAIK you can only inject the Router on components that have routes.

Alternatively you can inject the root router to a global service and then inject this service everywhere.

Jason
Guest

You need to specify the ROUTER_PROVIDERS when bootstrapping your application:

import { ROUTER_PROVIDERS } from 'angular2/router';

bootstrap(AppComponent, [ ROUTER_PROVIDERS ]);

Don’t forget to include the router.dev.js or router.min.js file into your main HTML file.

Jason
Guest

You need to mention the Location Strategy, try replacing this with your bootstrap :

bootstrap(AppComponent,[ROUTER_PROVIDERS,
    provide(LocationStrategy, { useClass: HashLocationStrategy })]);

Jason
Guest

I had this issue as well. I found a workaround in one of angular’s github issues (sorry I can’t find it to post a link). Basically, the Router instance wasn’t provided whenever it wasn’t found in your component’s template (or anywhere in the component tree above it).

For me, all I had to do was add <a [routerLink]="['/']"></a> into the upper-most component template. This will probably be fixed in future versions but as of now (a month after your question) the issue still remains.

P.S. I’m using the new router and not router-deprecated