简体   繁体   中英

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,....])

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.

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.

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

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

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.

PS I'm using the new router and not router-deprecated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM