原始异常:无法在角度2

时间:2017-03-03 10:17:07

标签: javascript angular

我在

上遇到了问题
  

无法在角度2

中读取未定义的属性'post'

在提交表单时,会调用一个函数,这里是代码

onSubmit() {
  console.log("onsubmit->", this.addForm.value);
  let addArray = this.addForm.value;
  this._employeeservice.addEmployeeCollection(addArray)
    .subscribe(sample => {
      this.dbemp.push(sample);
    });
  this.addForm.reset();
  this.SubmitToast();
}

addEmployeeCollection()代码在这里

addEmployeeCollection(addArray: EmployeeSchema) {
  let url: string = Constants.DOMAIN + Constants.CREATE_EMPLOYEE_ROUTE;
  console.log('addArray at emplyee service', addArray)
  var body = addArray;
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  let options = {
    headers: headers
  };
  let token = localStorage.getItem('realtoken');
  options.headers.set('Authorization', ` ${token}`);
  return this.http.post(url, body, options).map(res => res.json()).catch(this._errorHandler);
}

2 个答案:

答案 0 :(得分:1)

根据评论,我们了解到HTTP没有正确注入,导致this.http成为undefined

而不是像这样标记服务中的http:

export class EmployeeService {
  public http: Http;
}

它应该在构造函数中注入:

export class EmployeeService {
  constructor(public http: Http) { }
}

答案 1 :(得分:0)

通常,一旦您成功回电,清空表单会更安全。所以试试这个:

onSubmit() {
  console.log("onsubmit->", this.addForm.value);
  let addArray = this.addForm.value;
  this._employeeservice.addEmployeeCollection(addArray)
    .subscribe(sample => {
      this.dbemp.push(sample);
      this.addForm.reset(); //move this in the subscribe area
      this.SubmitToast();
    });
}