Angular 2 ES6注入Http

时间:2016-01-14 21:32:41

标签: ecmascript-6 angular

我试图弄清楚如何使用es6将http正确地注入我的班级。当我使用@inject时,我收到错误inject is not defined。我错过了其他一些我必须导入注入工作的东西吗?

import 'zone.js/lib/browser/zone-microtask';
import 'reflect-metadata';
import 'babel-polyfill';

import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {Http, Headers} from 'angular2/http';

import {Component, View, Input} from 'angular2/core';
import {RouteConfig, RouteParams, ROUTER_DIRECTIVES} from 'angular2/router';


@Component({
    selector: 'test-app',
    template: '<div>Hello my name is {{name}}. <button (click)="sayMyName()">Say my name</button></div>'
})
@inject('Http')
export class TestApp
{
    constructor(http)
    {
        this.name = 'Allencoded';
        this.http = http;
    }

    sayMyName()
    {
        console.log('My Name is ', this.name);
        console.log(this.http);
    }
}

1 个答案:

答案 0 :(得分:3)

这就是我最终的工作方式:

import { Http, HTTP_PROVIDERS } from 'angular2/http';

export class TestApp
{
    static get parameters() {
        return [[Http]];
    }

    constructor(http)
    {
        this.name = 'Allen';
        this.http = http;
    }
}

bootstrap(TestApp, [
  HTTP_PROVIDERS,
  provide(LocationStrategy, { useClass: HashLocationStrategy })
]);

取自: How to Inject Angular2 Http service into es6/7 Class?