如何在angular2中注入位置?

时间:2015-12-30 23:02:40

标签: angular angular2-routing

我认为注入Location的方式与注入Http的方式相同。然而,我的应用程序中断 - 如果我取消注释,页面不会呈现,公共位置:位置"在最后一行。据我所知,我有正确的import和providers数组:

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*/) { 

在我的index.html中,我有以下一行:

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

在我的引导代码中,我有:

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

不确定我是否错过了某些内容或当前版本是否已损坏。如果是第一种情况,我错过了什么?

1 个答案:

答案 0 :(得分:1)

你的NgModule中的

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

在您的组件中,您需要将其注入

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

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