6

我认为注入 Location 的方式与注入 Http 的方式相同。但是,我的应用程序中断 - 如果我在最后一行取消注释“公共位置:位置”,则页面不会呈现。据我所见,我有正确的导入和提供者数组:

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

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

4

1 回答 1

2

在你的 NgModule 中

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

在您的组件中,您需要注入它

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

 constructor(
     @Inject('locationObject') private locationObject: Location
 ) {}
于 2017-03-29T12:29:21.730 回答