[英]How to send http request using FormData in Angular 8?
在這里,我想使用 angular 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");
});
}
這種編碼習慣不好,不要在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");
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.