angular2 http:发布投掷错误

时间:2016-01-29 19:54:05

标签: http post angular

我正在使用angular2中的一个简单的CRUD应用程序,我在发布到后端服务器时遇到了麻烦。我的课程代码如下

export class PersonForm {
  data:Object;
  loading: boolean;
  personForm: ControlGroup;
  http:Http;
  constructor(personFormBuilder: FormBuilder) {
    this.personForm = personFormBuilder.group({
      'name': [],
      'age': []
    });
  }

  onSubmit(value:any) : void {
    console.log('you submitted these values: ', value);
    this.http.post("http://localhost:3000/people/create",JSON.stringify(value))
      .subscribe((res: Response) => {
        this.data = res.json();
        this.loading = true;
  });

 }

}

以上是在我的控制台中导致以下错误。我不确定什么是未定义的,因为我正在遵循我发现的每个例子:

EXCEPTION: Error during evaluation of "ngSubmit"
ORIGINAL EXCEPTION: TypeError: undefined is not an object
(evaluating 'this.http.post')

这是我的导入,以防万一我错过了一个组件

import {Component } from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {CORE_DIRECTIVES,FORM_DIRECTIVES, FormBuilder} from 'angular2/common';
import {HTTP_PROVIDERS, Http, Response, Headers} from 'angular2/http';
import {ControlGroup} from "angular2/common";

1 个答案:

答案 0 :(得分:1)

您需要在组件构造函数中注入http对象:

import {Http} from 'angular2/http';

@Component({
  (...)
})
export class PersonForm {
  data:Object;
  loading: boolean;
  personForm: ControlGroup;
  http:Http;

  constructor(private http: Http, personFormBuilder: FormBuilder) {
    (...)
  }
}

希望它可以帮到你, 亨利