网站搜索

typescript - Angular2 - browser_adapter.ts 原始异常:没有 Location 的提供者


这是一个快速问题……但我希望在我的应用的各个组件中获取当前的 URL,我不想从路由组件中推导这个值,因为它可能会被移除或随时间更改。所以我希望在 Angular2 中使用 Location 类。在我的组件中,我添加了以下内容……

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

在我的组件中,我在构造函数里声明了这个...

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

现在当我尝试使用这个时,我在控制台注意到错误... browser_adapter.ts:82 原始异常: 没有 Location 的提供者!

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);
    }
}

答案#1

要在组件中注入 Location,你需要在组件元数据中将 ROUTER_DIRECTIVE 作为指令传入。

这使得 Angular 能够正确地注入 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 从路由器本身获取 URL

来源:请参见示例部分。