以下是一个使用Angular发送表单数据的示例代码:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
formData = {
name: '',
email: ''
};
constructor(private http: HttpClient) { }
ngOnInit() {
}
onSubmit() {
// 发送原始表单数据
this.http.post('http://example.com/submit', this.formData)
.subscribe(response => {
console.log(response);
});
// 发送 JSON 数据
const jsonData = JSON.stringify(this.formData);
this.http.post('http://example.com/submit', jsonData, {
headers: { 'Content-Type': 'application/json' }
}).subscribe(response => {
console.log(response);
});
}
}
ngModel
指令绑定表单数据:
HttpClientModule
:import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { FormComponent } from './form/form.component';
@NgModule({
declarations: [
AppComponent,
FormComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
这样,当用户提交表单时,你可以选择发送原始的表单数据或者JSON数据到服务器。
上一篇:Angular:从Angularfirefirestore服务中获取路由的Scully插件失败,报错Error[ERR_REQUIRE_ESM]:require()ofESnotsupported。