我正在尝试将我的Angular表单中的数据发送到PHP文件。我正在使用Angular 4/5:
我的TypeScript文件:
export class HomeComponent implements OnInit {
constructor(private http: HttpClient) {}
sendForm() {
let formdata = document.querySelector('form');
let datajson = {
action: 'login',
username: formdata.username.value,
useremail: formdata.useremail.value,
usersubject: formdata.usersubject.value,
usermessage: formdata.usermessage.value
};
let apiurl = '../../assets/php/message.php';
this.http.post(apiurl,datajson)
.subscribe(data => {alert(datajson.data)})
.catch(error => {alert (error.status)});
}
}
错误:
error: core.js:1427 ERROR TypeError: Cannot read property 'post' of
undefined at HTMLButtonElement.eval (home.component.ts:168) at
ZoneDelegate.invokeTask (zone.js:425) at Object.onInvokeTask (core.js:4744)
at ZoneDelegate.invokeTask (zone.js:424) at Zone.runTask (zone.js:192) at
ZoneTask.invokeTask [as invoke] (zone.js:499) at invokeTask (zone.js:1540)
at HTMLButtonElement.globalZoneAwareCallback (zone.js:1566)
答案 0 :(得分:0)
你的代码需要在一个方法中,而不是全局的。
export class HomeComponent implements OnInit {
constructor(private http: HttpClient) {}
sendForm() {
let formdata = document.querySelector('form');
let datajson = {
action: 'login',
username: formdata.username.value,
useremail: formdata.useremail.value,
usersubject: formdata.usersubject.value,
usermessage: formdata.usermessage.value
};
let apiurl = '../../assets/php/message.php';
this.http.post(apiurl,datajson)
.subscribe(data => {alert(datajson.data)})
.catch(error => {alert (error.status)});
}
}
答案 1 :(得分:0)
我的猜测是你没有以正常方式调用sendForm
,而是在没有用箭头函数定义的回调中。所以this
不是指实际的组件,而是指其他的