在这里,我想使用角度HTTPClient服务器将html表单上的一些数据发送到后端。我曾经尝试过此代码,但没有将我的数据发送到后端服务器。
HTML
<form class="border text-center p-5 reg-frm" [formGroup]="ContactusForm">
<label>Full name :</label>
<input type="text" class="form-control box_border" aria-describedby="textHelp"
name="name" formControlName="name">
<button (click)="sendMessage()" type="button"
class="btn btn-info my-4 btn-block reg_btn ">Send Message</button>
</form>
TS文件
sendMessage(){
ContactusForm = this.fb.group({
name: ['', [Validators.required, Validators.maxLength(100)]],
})
const formData = new FormData();
formData.append('name', this.ContactusForm.value.name)
this.http.post<any>(url, formData).subscribe(res => {
console.log("data send");
});
}
答案 0 :(得分:1)
这种编码方式不好,不要在sendMessage方法中初始化formGroup,而应该尝试
首先使用单独的方法初始化表单数据,为此首先导入FormGroup和其他必需的东西,然后声明一个formGroup变量/属性
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
//declare property
constactUsPayload: FormGroup;
//In Oninit- initialize payload.
ngOnInit(){
this.initialize_payload();
}
initialize_payload() {
this.contactUsPayload = this._fb.group({
'name': this._fb.control('', Validators.required, Validators.maxLength(100)]),
});//you can declare more fields based on your future requirements
}
sendMessage(){
this.http.post<any>(url, this.contactUsPayload.value.name).subscribe(res => {
console.log("data send");
});
}