Peter Pei Guo
Peter Pei Guo

Reputation: 7870

How can I inject Location in angular2?

I thought it would be the same way to inject Location just like how I inject Http. However my app breaks - the page does not render, if I uncomment "public location: Location" in the last line. As far as I can see, I have the correct import and providers array:

import {Component} from 'angular2/core';
import {
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    RouteConfig,
    Location,
    LocationStrategy,
    HashLocationStrategy
} from 'angular2/router';

import {TaskForm} from './task_form';
import {TaskList} from './task_list';
import {AboutUs} from './about_us';

@Component({
    selector: 'task-app',
    templateUrl: 'app/task_app.html',
    providers: [ROUTER_PROVIDERS],
    directives: [TaskForm, TaskList, ROUTER_DIRECTIVES]
})
@RouteConfig([
    {path: '/', component: TaskApp, as: 'Home'},
    {path: '/about_us', component: AboutUs, as: 'aboutUs'}
])
export class TaskApp {  
    constructor(/*public location: Location*/) { 

In my index.html, I have the following line:

<script src="https://code.angularjs.org/2.0.0-beta.0/router.dev.js"></script>

In my bootstrap code, I have:

import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {provide} from 'angular2/core';

import {
    ROUTER_DIRECTIVES,
    ROUTER_PROVIDERS,
    RouteConfig,
    Location,
    LocationStrategy,
    HashLocationStrategy
} from 'angular2/router';

import {TaskApp} from './task_app';
import {MyService} from './my_service'

bootstrap(TaskApp, [HTTP_PROVIDERS, ROUTER_PROVIDERS, MyService, provide(LocationStrategy, {useClass: HashLocationStrategy})]);

Not sure whether I missed something or the current build is broken. If it is the first case, what did I miss?

Upvotes: 6

Views: 5720

Answers (1)

t0mpl
t0mpl

Reputation: 5025

in your NgModule

  providers: [ 
     { provide: 'locationObject', useValue: location}
  ]

in your component you need to Inject it so

import { Component, Inject } from '@angular/core';

 constructor(
     @Inject('locationObject') private locationObject: Location
 ) {}

Upvotes: 3

Related Questions