繁体   English   中英

如何在 Angular 8 中使用 FormData 发送 http 请求?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM