【问题标题】:Angular 2 ES6 Inject HttpAngular 2 ES6 注入 Http
【发布时间】:2016-04-20 09:39:33
【问题描述】:

我试图弄清楚如何使用 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);
    }
}

【问题讨论】:

  • OP,gitter gitter.im/angular/angular 也值得一试
  • 那是因为 @inject 没有定义,字面意思。它是@Inject(驼峰式,与其他 ng2 装饰器一样)。它应该被导入(作为其他 ng2 装饰器)。
  • 我试过了,还是不行。我尝试导入它然后使用@Inject 并尝试@inject。两者都不起作用

标签: ecmascript-6 angular


【解决方案1】:

这就是我最终实现它的方式:

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    相关资源
    最近更新 更多