简体   繁体   English

如何在angular2中注入位置?

[英]How can I inject Location in angular2?

I thought it would be the same way to inject Location just like how I inject Http. 我认为注入位置就像注入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和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*/) { 

In my index.html, I have the following line: 在我的index.html中,我有以下行:

<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? 如果是第一种情况,我错过了什么?

in your NgModule 在你的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
 ) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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