Angular2-browser_adapter.ts原始例外:没有位置信息提供者 [英] Angular2 - browser_adapter.ts ORIGINAL EXCEPTION: No provider for Location
问题描述
这是一个快速的问题..但是我希望在各种组件中获取我的应用程序的当前URL,我不想从我的路由组件中获取此值,因为它可能会被及时删除/更改.因此,我希望使用Angular2中的Location
类.在我的组件中,添加以下内容...
this is a quick question.. but I wish to get the current url of my app in various components, I don't want to derive this value from my routing component as that may be removed / changed in time. So I wish to work with the Location
class in Angular2. In my component I add the following...
import {Location} from '@angular/common';
在我的组件中,我在构造函数中声明了这一点...
in my component I declare this in my constructor...
constructor(public translate:TranslateService, router:Router, private location: Location)
现在,当我尝试使用它时,我注意到控制台中的错误... browser_adapter.ts:82 ORIGINAL EXCEPTION: No provider for Location!
Now when I try to work with this I notice the error in my console... browser_adapter.ts:82 ORIGINAL EXCEPTION: No provider for Location!
位置类位于@angular/common
中?我看不到我怎么在这里犯错了?我正在使用Angular2版本候选4.这是我的代码的整体样子,我对其进行了编辑以使其不那么令人沮丧:
The location class is located in @angular/common
? I can't see how I have made a mistake here? I am using Angular2 release candidate 4. Here's what my code looks like altogether, I have edited this to make it less overwhelming:
import {Location} from '@angular/common';
@Component({
selector: 'my-app',
directives: [ ],
pipes: [ ],
templateUrl: 'src/main.html'
})
class MyComponent {
constructor( private location: Location) {
console.log(location);
}
}
推荐答案
要在组件中注入Location
,您需要将ROUTER_DIRECTIVE
作为指令传递给组件元数据.
To inject Location
in a component you need to pass ROUTER_DIRECTIVE
as directive in component metadata.
此功能可启用角度来正确注入Location
.
This enabled angular to inject the Location
properly.
import {Location} from '@angular/common';
import { ROUTER_DIRECTIVES } from '@angular/router'
@Component({
selector: 'my-app',
directives: [ ROUTER_DIRECTIVES],
pipes: [ ],
templateUrl: 'src/main.html'
})
class MyComponent {
}
您还可以通过this.router.url
源:请参见示例部分.
Source : see the example section.
这篇关于Angular2-browser_adapter.ts原始例外:没有位置信息提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!