尝试保存新对象时出现错误。这就是说验证器需要name字段,因此至少我知道验证器正在工作。但是我在表单中有一个名为“名称”的字段,从我在其他代码中可以看到的,我也正在传递该名称字段。我看不到我想念的是什么。
错误
(node:19000) UnhandledPromiseRejectionWarning: ValidationError: Asdf validation failed: name: Path `name` is required.
这是我的HTML表单。
<form [formGroup]="form" (submit)="onSave()" *ngIf="!isLoading">
<mat-form-field>
<input matInput type="text" formControlName="name" placeholder="Name">
<mat-error *ngIf="form.get('name').invalid">Please enter an ASDF name</mat-error>
</mat-form-field>
<button mat-raised-button color="accent" type="submit">Save</button>
</form>
这是我的创建组件。
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { AsdfService } from './../asdfs.service';
import { Asdf } from '../asdf.model';
@Component({
selector: 'app-asdf-create',
templateUrl: './asdf-create.component.html',
styleUrls: ['./asdf-create.component.css']
})
export class AsdfCreateComponent implements OnInit {
obj: Asdf;
isLoading = false;
form: FormGroup;
private mode = 'create';
private id: string;
constructor(
public service: AsdfService,
public route: ActivatedRoute
) { }
ngOnInit() {
this.form = new FormGroup({
name: new FormControl(null, {validators: [Validators.required, Validators.minLength(3)]
});
this.route.paramMap.subscribe((paramMap: ParamMap) => {
if (paramMap.has('id')) {
this.mode = 'edit';
this.id = paramMap.get('id');
this.isLoading = true;
this.service.getOne(this.id).subscribe(objData => {
this.isLoading = false;
this.obj = {
id: objData._id,
name: objData.name
};
this.form.setValue({
name: this.obj.name
});
});
} else {
this.mode = 'create';
this.id = null;
}
});
}
onSave() {
if (this.form.invalid) { return; }
this.isLoading = true;
if (this.mode === 'create') {
this.service.add(
this.form.value.name
);
} else {
this.service.update(
this.id,
this.form.value.name
);
}
this.form.reset();
}
}
最后是服务代码。
private apiAddress = 'http://localhost:3000/api/';
private plural = 'asdfs';
add(name: string) {
const objData = new FormData();
objData.append('name', name);
this.http
.post<{ message: string; obj: Asdf }>(this.apiAddress + this.plural, objData)
.subscribe(responseData => { this.router.navigate(['/' + this.plural]);
});
}