2016-07-19 47 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從路由器本身你的網址:見實施例部分。

相關問題