簡體   English   中英

如何在angular2中注入位置?

[英]How can I inject Location in angular2?

我認為注入位置就像注入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})]);

不確定我是否遺漏了某些內容或當前版本是否已損壞。 如果是第一種情況,我錯過了什么?

在你的NgModule中

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

在您的組件中,您需要將其注入

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