2016-07-19 48 views
2

这是一个快速的问题..但我希望得到我的应用程序的当前网址在各种组件中,我不想从我的路由组件中派生此值因为这可能会被及时删除/更改。所以我希望在Angular2中使用Location类。在我的组件我添加以下...Angular2 - browser_adapter.ts原来的例外:没有提供商的位置

import {Location} from '@angular/common'; 
在我的组件

我宣布这在我的构造......

constructor(public translate:TranslateService, router:Router, private location: Location) 

现在,当我试图用这个工作,我注意到在我的错误控制台... browser_adapter.ts:82 ORIGINAL EXCEPTION: No provider for Location!

位置类位于@angular/common?我看不出我在这里犯了什么错误?我使用Angular2候选版本4.下面是我的代码看起来干脆,我已经编辑这使它不那么铺天盖地:

import {Location} from '@angular/common'; 

@Component({ 
    selector: 'my-app', 
    directives: [ ], 
    pipes: [ ], 
    templateUrl: 'src/main.html' 
}) 
class MyComponent { 

    constructor(private location: Location) { 
     console.log(location); 
    } 
} 

回答

0

要在你需要传递ROUTER_DIRECTIVE在组件元数据指令的成分注入Location

这使角度正确地注入Location

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从路由器本身你的网址:见实施例部分。

相关问题