Spring Boot+Angular项目Reactive Forms无法填充后端返回数据如何解决
Spring Boot + Angular 学生系统表单自动填充问题修复
问题描述
使用Spring Boot和Angular搭建学生系统时,更新联系人信息需要将后端返回的信息自动填充到表单对应字段,后端接口返回数据正常,但表单无法成功赋值。
原有问题代码
后端接口(Java)
@GetMapping("/Person/{personId}") public Person getPersonID(@PathVariable(value = "personId") Integer personId) { Person person = editorService.findBypersonId(personId); return person; }
前端代码
组件逻辑(TypeScript)
data: Person = new Person(); ngOnInit() { this.reloadData(); this.reloadForm(); } reloadData() { this.personService.getPErsonId(this.personId).subscribe(response => { this.data = response; }); } reloadForm() { this.ilanOlusturForm = new FormGroup({ personName: new FormControl( this.data ? this.data.personName : "", [Validators.required] ), }); } export class Person{ name:string; surname:string; .... }
模板代码(HTML)
<nb-card> <nb-card-body> <nb-stepper #stepper> <nb-step [stepControl]="ilanOlusturForm" > <form [formGroup]="ilanOlusturForm" class="step-container"> <div class="row"> <div class="col-sm-3"> <div class="form-group"> <label class="label">Personel</label> <input type="text" nbInput fullWidth fieldSize="small" formControlName="personName"> </div> </div> </div> </form> </nb-step> </nb-stepper> </nb-card-body> </nb-card>
问题原因
前端HTTP请求属于异步操作,原有代码在ngOnInit钩子中同步调用reloadData和reloadForm,执行reloadForm初始化表单时,后端请求还未返回结果,this.data仍为初始的空Person实例,因此表单赋值失败。
修复代码
将表单初始化逻辑移动到异步请求的回调函数中,等后端数据返回后再初始化表单:
ngOnInit() { this.reloadData(); } reloadData() { this.personService.getPErsonId(this.personId).subscribe(response => { this.data = response; // 等待数据返回后再初始化表单 this.reloadForm(); }); } reloadForm() { this.ilanOlusturForm = new FormGroup({ personName: new FormControl(this.data ? this.data.personName : "", [Validators.required]), }); }
运行效果

内容的提问来源于stack exchange,提问作者zdnmn
相关产品推荐
相关产品推荐

