简体   繁体   English

Angular2路由器未定义

[英]Angular2 router undefined

I want to use the Router to retrieve the current URL(router) being displayed. 我想使用路由器检索正在显示的当前URL(路由器)。 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. 我读到有另一种通过使用“位置”来获取URL的方法,但这不是推荐的方法。 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: ROUTER_PROVIDERS已指定为:

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

Your index.html should contain 您的index.html应该包含

<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. AFAIK,您只能在具有路由的组件上注入Router

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: 引导应用程序时,需要指定ROUTER_PROVIDERS

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. 不要忘记在您的主HTML文件中包含router.dev.jsrouter.min.js文件。

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). 我在angular的github问题之一中找到了解决方法(很抱歉,找不到发布链接的链接)。 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. 对我来说,我要做的就是将<a [routerLink]="['/']"></a>添加到最上方的组件模板中。 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 PS我使用的是新路由器,而不是不推荐使用的路由器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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