简体   繁体   中英

Angular2 - browser_adapter.ts ORIGINAL EXCEPTION: No provider for 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) 

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!

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

To inject Location in a component you need to pass ROUTER_DIRECTIVE as directive in component metadata.

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 {
    }

You could also get URL from router itself you by this.router.url

Source : see the example section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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