我正在学习Angular 6
,并且已经在Django
中创建了REST API。
我必须以 JSON 格式将表单数据发送到服务器。
这就是我在组件中所做的。
my.component.ts
import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {AmountGivenService} from '../amount-given.service';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-amount-given-add',
templateUrl: './amount-given-add.component.html',
styleUrls: ['./amount-given-add.component.css']
})
export class AmountGivenAddComponent implements OnInit {
addMoneyForm: FormGroup;
submitted = false;
contact_id: string;
constructor(
private formBuilder: FormBuilder,
private amountGivenService: AmountGivenService,
private route: ActivatedRoute
) { }
ngOnInit(): void {
this.route.params.subscribe(
param => {
this.contact_id = param['contact_id'];
}
);
console.log(this.contact_id);
this.addMoneyForm = this.formBuilder.group({
amount: new FormControl('', [
Validators.required
]),
duration: new FormControl()
});
}
get f() {
return this.addMoneyForm.controls;
}
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.addMoneyForm.invalid) {
console.log('invalid');
return;
}
console.log(this.addMoneyForm.getRawValue());
let data = this.addMoneyForm.value;
data = JSON.parse(data);
// append contact_id
data.contact_id = this.contact_id;
data = JSON.stringify(data);
this.amountGivenService.add(data).subscribe(res => {
console.log('req completed', res);
});
}
}
在发送请求之前,我需要附加contact_id
。
但是在提交表单时,页面正在刷新,表单以GET方法提交。
正在从上面的组件文件中删除此代码元素,并且正在将请求发送到服务器。
data = JSON.parse(data);
// append contact_id
data.contact_id = this.contact_id;
data = JSON.stringify(data);
如何将值附加到组件中的表单数据?
编辑2: my.component.html
<form [formGroup]="addMoneyForm" (submit)="onSubmit()" id="form-add-money" #formDir="ngForm">
<label for="input-amount">Amount</label>
<input formControlName="amount"
id="input-amount"
class="form-control"
placeholder="Amount">
<div *ngIf="submitted && f['amount'].invalid" class="text-danger">
<div *ngIf="f['amount'].errors.required">Amount is required</div>
</div>
</div>
<label for="input-duration">Duration (in days)</label>
<input formControlName="duration" type="number" id="input-duration" class="form-control" placeholder="Duration (in days)">
</form>
<button class="btn btn-success" type="submit" form="form-add-money" [disabled]="!formDir.valid">
<i class="fa fa-save">Save</i>
</button>
答案 0 :(得分:1)
let data = this.addMoneyForm.value;
data = JSON.parse(data);
// append contact_id
data.contact_id = this.contact_id;
data = JSON.stringify(data);
this.amountGivenService.add(data).subscribe(res => {
console.log('req completed', res);
});
这毫无意义:
amountGivenService
不应(而且显然也不应)将JSON字符串作为参数。它应该(而且确实)接受类型化的对象。所有你应该拥有的
const data = this.addMoneyForm.value;
data.contact_id = this.contact_id;
this.amountGivenService.add(data).subscribe(res => {
console.log('req completed', res);
});
此外,在模板中,“提交”按钮位于表单外部。它必须在里面。