我需要先调用 API 获取一些值放在我的表单中然后提交它。我喜欢避免使用带有隐藏输入的表单并希望即时创建它。我的伪代码
submitMyform() {
//first i call an API and get some data
var mydata = this.http.get()...
this.signForm = new FormGroup({
'Name': new FormControl(mydata.name),
'Age': new FormControl(mydata.age)
});
this.signForm.submit() //Wished this method existed
}
我希望我的浏览器重定向到我提交表单的页面。
编辑:对不起..!我最关心的是如何提交这个表格。不获取数据并填充表单。我的代码只是一个模板..这是我缺少的 this.signForm.submit() 方法
最佳答案
你在这里做的错误是你无法访问 mydata
中的数据没有订阅它,因为 http.get()
返回 Observable
您可以使用订阅
submitMyform() {
//first i call an API and get some data
var mydata = this.http.get()...
mydata.subscribe((data) =>{
this.signForm = new FormGroup({
'Name': new FormControl(mydata.name),
'Age': new FormControl(mydata.age)
});
this.http.post('url', this.signForm);
});
}
或异步/等待
async submitMyform() {
//first i call an API and get some data
var mydata = await this.http.get().toPromise();
this.signForm = new FormGroup({
'Name': new FormControl(mydata.name),
'Age': new FormControl(mydata.age)
});
this.http.post('url', this.signForm);
}
更新:
我已经尝试了几件事来在 Angular 中通过重定向发送 post 请求。但唯一对我有用的是创建隐藏的
<form>
为此,我创建了此方法
submitForm(action, method, formGroup: FormGroup) {
const form = document.createElement('form');
form.style.display = 'none';
form.method = method;
form.action = action;
let input;
for (const [key, value] of Object.entries(formGroup.value)) {
input = document.createElement('input');
input.name = key;
input.id = key;
input.value = value;
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}
这里最好的方法是在没有
appendChild()
的情况下提交它。但它会产生这个错误Submit was canceled because form is no connected.
关于angular - 如何动态创建表单并在 Angular 7 中提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55122374/