我在
上遇到了问题无法在角度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);
}
答案 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();
});
}