如何注入Angular2 HTTP服务到ES6 / 7类? [英] How to Inject Angular2 Http service into es6/7 Class?

查看:310
本文介绍了如何注入Angular2 HTTP服务到ES6 / 7类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用ES6 / 7(通天塔 - 第1阶段)?而不是打字稿,如何服务,特别是HTTP,注射

下面是我的部分JS:

 进口{组件,注入,查看,CORE_DIRECTIVES,ViewEncapsulation}从'angular2 / angular2';
从angular2 / HTTP'进口{}的Http;@零件({
  选择:登录
})
@视图({
  templateUrl:./components/login/login.html',
  styleUrls:['组件/登录/ login.css'],
  指令:[CORE_DIRECTIVES]
  封装:ViewEncapsulation.Emulated
})
出口类登录{
  构造函数(@注入(HTTP)HTTP){
    的console.log('HTTP',HTTP);
  }  认证(用户名,密码){
    // this.http.get('/登录');
  }
}

我曾尝试:

 出口类登录{
  构造函数(@注入(HTTP)HTTP){
    的console.log('HTTP',HTTP);
  }
}
/ ****** /
@Inject(HTTP)
出口类登录{
  构造函数(HTTP){
    的console.log('HTTP',HTTP);
  }
}
/ ****** /
出口类登录{
  构造函数(HTTP:HTTP){
    的console.log('HTTP',HTTP);
  }
}
/ ****** /
出口类登录{
  构造器(HTTP = HTTP){
    的console.log('HTTP',HTTP);
  }
}
/ ****** /
出口类登录{
  构造函数(HTTP){
    this.http =新的HTTP()
    的console.log('HTTP',this.http);
  }
}
/ ****** /
出口类登录{
  构造器(HTTP =新的HTTP()){
    的console.log('HTTP',HTTP);
  }
}

除了第一个编译。别人给我的访问要么在HTTP类或HTTP实例。但是,没有工作。

我试着以下由埃里克·马丁内斯在他的评论中引用的讨论。现在Login.js:

 进口{组件,注入,查看,CORE_DIRECTIVES,ViewEncapsulation}从'angular2 / angular2';
进口{HTTP_BINDINGS,HTTP,BaseRequestOptions,RequestOptions,RequestMethods}从'angular2 / HTTP';@零件({
  选择:登录
})
@视图({
  templateUrl:./components/login/login.html',
  styleUrls:['组件/登录/ login.css'],
  指令:[CORE_DIRECTIVES]
  封装:ViewEncapsulation.Emulated,
  绑定:[HTTP]
})
出口类登录{  构造函数(HTTP){
    this.http = HTTP;
    的console.log('HTTP',HTTP);
  }  验证(usernameEl,passwordEl){
    VAR用户名= usernameEl.value;
    VAR密码= passwordEl.value;
    的console.log(用户名,用户名,密码);    // this.http.get('/登录');
  }
}Login.parameters = [HTTP];

现在编译,但会生成以下错误:


  

未捕获的(以诺)NoBindingError {消息:没有供应商对于HTTP!
  (登录 - > HTTP),堆栈:错误:DIException↵在
  NoBindingError.BaseExce ... or._new
  (的http://本地主机:3000 / bundle.js:7319:22 ),键:数组[2],喷油器:
  数组[2]} constructResolvingMessage:(键)参数:(...)来电:
  (...)长度:1name:原型:Object__proto__:()方面:(......)喷油器:数组[2] 0:Injector1:Injectorlength:
  2__proto__:数组[0]键:数组[2]消息:没有供应商对于HTTP!
  (登录 - > HTTP)栈:错误:DIException↵在
  NoBindingError.BaseException [作为构造]
  (的http://本地主机:3000 / bundle.js:8400:24 )↵在
  NoBindingError.AbstractBindingError [作为构造]
  (的http://本地主机:3000 / bundle.js:9066:17 )↵在新NoBindingError
  (的http://本地主机:3000 / bundle.js:9102:17 )↵在Injector._throwOrNull
  (的http://本地主机:3000 / bundle.js:7469:20 )↵在
  Injector._getByKeyDefault(的http://本地主机:3000 / bundle.js:7516:22 )↵结果
  在Injector._getByKey(的http://本地主机:3000 / bundle.js:7461:26 )↵在
  Injector._getByDependency(的http://本地主机:3000 / bundle.js:7447:26 )↵结果
  在Injector._instantiate(的http://本地主机:3000 / bundle.js:7339:37 )↵结果
  在Injector._instantiateBinding
  (的http://本地主机:3000 / bundle.js:7330:26 )↵在Injector._new
  (的http://本地主机:3000 / bundle.js:7319:22 )< STRONG>原:__



解决方案

既然你有 @Decorators 通天启用

...我会微调这个答案与你的特定设置工作。

1。你错过了<一个href=\"https://angular.io/docs/ts/latest/api/http/HTTP_PROVIDERS-let.html]\">HTTP_PROVIDERS

的HTTP_PROVIDERS常数包括若干处理HTTP请求/响应所需要的功能。

 从'angular2 / HTTP'进口{HTTP,HTTP_PROVIDERS};@零件({
  选择:登录,
  供应商:[HTTP_PROVIDERS]
})

2。您需要desugar的DI(依赖注入)语法

@alexpods的回答提及。

删除静态类型

 构造函数(HTTP){

@注入处理的DI隐而是仅在Angular2 +打字稿支持。由于您使用的Angular2 + ES6你需要一个静态的getter参数附加到你的类提供特定ES6当量。

 静态get参数(){
    返回[[HTTP]];
}

3。您需要将HTTP实例绑定到你的类构造函数

通过这样做,它将成为您访问认证()方法。

 构造函数(HTTP){
    this.http = HTTP;
    的console.log('HTTP',this.http);
}


...并全面推行:

 进口{组件,注入,查看,CORE_DIRECTIVES,ViewEncapsulation}从'angular2 / angular2';
从angular2 / HTTP'进口{HTTP,HTTP_PROVIDERS};@零件({
  选择:登录,
  //需要的Http
  供应商:[HTTP_PROVIDERS]
})
@视图({
  templateUrl:./components/login/login.html',
  styleUrls:['组件/登录/ login.css'],
  指令:[CORE_DIRECTIVES]
  封装:ViewEncapsulation.Emulated
})
出口类登录{
  构造函数(HTTP){
    //绑定HTTP到施工过程中的类
    //所以它的可用来验证()
    this.http = HTTP;
  }  // Angular2 DI desugar'd
  静态get参数(){
    返回[[HTTP]];
  }  认证(用户名,密码){
    this.http.get('/登录');
  }
}

题外话:我知道一个事实,这个工作,因为我使用它的&LT; NG2-降价&GT; 组件<一href=\"https://github.com/evanplaice/evanplaice.com/blob/master/app/components/markdown/markdown.js\">EvanPlaice.com.

If I use es6/7 (babel - stage 1) instead of TypeScript, how are services, and specifically Http, injected?

Here's my component JS:

import {Component, Inject, View, CORE_DIRECTIVES, ViewEncapsulation} from 'angular2/angular2';
import {Http} from 'angular2/http';

@Component({
  selector: 'login'
})
@View({
  templateUrl: './components/login/login.html',
  styleUrls: ['components/login/login.css'],
  directives: [CORE_DIRECTIVES],
  encapsulation: ViewEncapsulation.Emulated
})
export class Login {
  constructor(@Inject(Http) http) {
    console.log('http', http);
  }

  authenticate(username, password) {
    // this.http.get('/login');
  }
}

I have tried:

export class Login {
  constructor(@Inject(Http) http) {
    console.log('http', http);
  }
}
/********************/
@Inject(Http)
export class Login {
  constructor(http) {
    console.log('http', http);
  }
}
/********************/
export class Login {
  constructor(Http: http) {
    console.log('http', http);
  }
}
/********************/
export class Login {
  constructor(http = Http) {
    console.log('http', http);
  }
}
/********************/
export class Login {
  constructor(Http) {
    this.http = new Http()
    console.log('http', this.http);
  }
}
/********************/
export class Login {
  constructor(http = new Http()) {
    console.log('http', http);
  }
}

All but the first compiles. Others give me access to either the Http class or an http instance. But none works.

I tried to following the discussion referenced by Eric Martinez in his comment. Login.js now:

import {Component, Inject, View, CORE_DIRECTIVES, ViewEncapsulation} from 'angular2/angular2';
import {HTTP_BINDINGS, Http, BaseRequestOptions, RequestOptions, RequestMethods} from 'angular2/http';

@Component({
  selector: 'login'
})
@View({
  templateUrl: './components/login/login.html',
  styleUrls: ['components/login/login.css'],
  directives: [CORE_DIRECTIVES],
  encapsulation: ViewEncapsulation.Emulated,
  bindings: [Http]
})
export class Login {

  constructor(http) {
    this.http = http;
    console.log('http', http);
  }

  authenticate(usernameEl, passwordEl) {
    var username = usernameEl.value;
    var password = passwordEl.value;
    console.log('username', username, password);

    // this.http.get('/login');
  }
}

Login.parameters = [Http];

It compiles now but generates the following error:

Uncaught (in promise) NoBindingError {message: "No provider for Http! (Login -> Http)", stack: "Error: DI Exception↵ at NoBindingError.BaseExce…or._new (http://localhost:3000/bundle.js:7319:22)", keys: Array[2], injectors: Array[2]}constructResolvingMessage: (keys)arguments: (...)caller: (...)length: 1name: ""prototype: Object__proto__: ()context: (...)injectors: Array[2]0: Injector1: Injectorlength: 2__proto__: Array[0]keys: Array[2]message: "No provider for Http! (Login -> Http)"stack: "Error: DI Exception↵ at NoBindingError.BaseException [as constructor] (http://localhost:3000/bundle.js:8400:24)↵ at NoBindingError.AbstractBindingError [as constructor] (http://localhost:3000/bundle.js:9066:17)↵ at new NoBindingError (http://localhost:3000/bundle.js:9102:17)↵ at Injector._throwOrNull (http://localhost:3000/bundle.js:7469:20)↵ at Injector._getByKeyDefault (http://localhost:3000/bundle.js:7516:22)↵
at Injector._getByKey (http://localhost:3000/bundle.js:7461:26)↵ at Injector._getByDependency (http://localhost:3000/bundle.js:7447:26)↵
at Injector._instantiate (http://localhost:3000/bundle.js:7339:37)↵
at Injector._instantiateBinding (http://localhost:3000/bundle.js:7330:26)↵ at Injector._new (http://localhost:3000/bundle.js:7319:22)"proto: __

解决方案

Since you have @Decorators enabled in Babel

...I'll fine-tune this answer to work with your specific setup.

1. You're missing HTTP_PROVIDERS

The HTTP_PROVIDERS constant includes a number of functions required to handle HTTP requests/responses.

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

@Component({
  selector: 'login',
  providers: [ HTTP_PROVIDERS ]
})

2. You need to desugar the DI (Dependency Injection) syntax

As mentioned in @alexpods' answer.

Remove the static typing

constructor(http) {

@Inject handles DI implicitly but is only supported in Angular2+Typescript. Since you're using Angular2+ES6 you need to attach a static getter parameter to your class to provide the ES6-specific equivalent.

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

3. You need to bind the Http instance to your class in the constructor

By doing this, it will become accessible in your authenticate() method.

constructor(http) {
    this.http = http;
    console.log('http', this.http);
}


...and the full implementation:

import {Component, Inject, View, CORE_DIRECTIVES, ViewEncapsulation} from 'angular2/angular2';
import {Http, HTTP_PROVIDERS} from 'angular2/http';

@Component({
  selector: 'login',
  // required for Http
  providers: [ HTTP_PROVIDERS ]
})
@View({
  templateUrl: './components/login/login.html',
  styleUrls: ['components/login/login.css'],
  directives: [CORE_DIRECTIVES],
  encapsulation: ViewEncapsulation.Emulated
})
export class Login {
  constructor(http) {
    // bind http to your class during construction
    //   so it's available to authenticate()
    this.http = http;
  }

  // Angular2 DI desugar'd
  static get parameters() {
    return [[Http]];
  }

  authenticate(username, password) {
    this.http.get('/login');
  }
}

Aside: I know for a fact this works because I'm using it for the <ng2-markdown> component on EvanPlaice.com.

这篇关于如何注入Angular2 HTTP服务到ES6 / 7类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆