Angular 角度-将其他表单数据传递到服务器
我有一个带有prod_name、prod_desc、prod_price的基本角度表单,这些当然是我希望在提交表单时发送到服务器的表单 然而,我想发送额外的和平的数据,我不想使隐藏的输入字段 因此,表单的剥离版本如下所示:Angular 角度-将其他表单数据传递到服务器,angular,angular-forms,angular-controller,Angular,Angular Forms,Angular Controller,我有一个带有prod_name、prod_desc、prod_price的基本角度表单,这些当然是我希望在提交表单时发送到服务器的表单 然而,我想发送额外的和平的数据,我不想使隐藏的输入字段 因此,表单的剥离版本如下所示: <form [formGroup]="productForm" (ngSubmit)="onFormSubmit(productForm.value)"> <mat-form-field class="example-full-width">
<form [formGroup]="productForm" (ngSubmit)="onFormSubmit(productForm.value)">
<mat-form-field class="example-full-width">
<input matInput placeholder="Product Name" formControlName="prod_name"
[errorStateMatcher]="matcher">
</mat-form-field>
<!-- Additional two form fields omitted for clarity -->
<div class="button-row">
<button type="submit" [disabled]="!productForm.valid" mat-flat-button color="primary"><mat-icon>save</mat-icon></button>
</div>
</form>
在onFormSubmit函数中,我还希望将当前日期传递给服务器。
表单模板中的隐藏字段不是选项。
我想在调用服务之前在onFormSubmit函数中执行此操作,但我被卡住了
对于如何基本上设置附加数据以及表单数据,例如日期并将其发送到服务器,我将不胜感激。您可以复制表单数据,然后向其中添加任何内容
onFormSubmit(form: NgForm) {
const dataForSubmit = {...form.value}; // copies the form data into a new variable
dataForSubmit.otherProperty = 'what ever you want'; // add whatever data is needed
this.api.addProduct(dataForSubmit)
.subscribe(res => {
let id = res.id;
this.router.navigate(['/product-details', id]);
}, err => {
console.log(err);
});
}
在我的应用程序中,我经常为所有数据定义一个接口。我将数据输入该接口,只将我想要的字段复制到表单中。然后在保存时,将表单中的更改复制到原始对象上
接口
当然,系统id不会出现在UI中
组件代码
解决方案比我想象的要简单得多。我在寻找有角度的物体和一些函数时迷失了方向。也许也可以使用数组表示法将数据添加到对象中而不复制它?还是抄袭更好?谢谢你的回答,也谢谢你的设计模式建议!表单对象本身productForm上有很多额外的内容。您可以将其输出到控制台进行查看。您最好只将该对象中的值复制到另一个对象上并进行编辑。是的,实际上onFormSubmit函数只向其传递值,它在模板ngSubmit=onFormSubmitproductForm.value中看起来是这样的,这也会向函数传递较小的对象,因为JavaScript会按值向函数传递参数。我知道这不是一个很大的速度提升,而是一个很小的东西。啊,是的,我明白了。让我困惑的是:form:NgForm作为数据类型。我现在已经删除了它,它是其他人留下的代码,它也让我陷入了错误的轨道,在NgForm中搜索某些函数以添加新数据,而没有意识到它实际上是普通的JavaScript对象。
onFormSubmit(form: NgForm) {
const dataForSubmit = {...form.value}; // copies the form data into a new variable
dataForSubmit.otherProperty = 'what ever you want'; // add whatever data is needed
this.api.addProduct(dataForSubmit)
.subscribe(res => {
let id = res.id;
this.router.navigate(['/product-details', id]);
}, err => {
console.log(err);
});
}
export interface Product {
id: number;
productName: string;
productCode: string;
}
// Update the data on the form
// after a get
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode
});
// The save
saveProduct(): void {
if (this.productForm.valid) {
// Copies any changed form values over the original product values
const p = { ...this.product, ...this.productForm.value };
// Call the http service put to save the data `p`
}
}