【问题标题】:Reactive Forms value is null反应式表单值为空
【发布时间】:2021-09-27 08:12:01
【问题描述】:

我正在构建一个带有 spring boot 和 angular 的学生系统。当我想更新联系信息时,我希望将来自后端的信息写入自动表单中的必要位置。我的代码部分就像下面的机器人一样,它没有写入任何值,尽管后端部分充满了数据。


@GetMapping("/Person/{personId}")
public Person getPersonID(@PathVariable(value = "personId") Integer personId) {
  Person person = editorService.findBypersonId(personId);
  return person;
}

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;
  ....
}


<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>
                

  ngOnInit() {
  this.reloadData();
  
}

reloadData() {
  this.personService.getPErsonId(this.personId).subscribe(response => {
    this.data = response;
    
    // Move this line to here
    this.reloadForm();
    
  });
}

reloadForm() {
  this.ilanOlusturForm = new FormGroup({
    personName: new FormControl(this.data ? this.data.personName : "", [Validators.required]),
  });
}

【问题讨论】:

  • this.reloadForm(); 这个调用里面你订阅reloadData 的声明。由于reloadData 是异步操作。

标签: angular spring-boot angular-reactive-forms


【解决方案1】:

你应该把this.reloadForm();移到reloadData()里面。

data: Person = new Person();

ngOnInit() {
  this.reloadData();
  
}

reloadData() {
  this.personService.getPErsonId(this.personId).subscribe(response => {
    this.data = response;
    
    // Move this line to here
    this.reloadForm();
    
  });
}

reloadForm() {
  this.ilanOlusturForm = new FormGroup({
    personName: new FormControl(this.data ? this.data.personName : "", [Validators.required]),
  });
}


export class Person {


  name: string;
  surname: string;
  ....

}

【讨论】:

  • 您好,首先感谢您的回复,但我遇到了错误。错误 ss 我附在问题上。
  • @zdnmn 我明白了,也许你错过了 HTML 中的 [formGroup]="ilanOlusturForm",你能检查一下吗?如果它已经存在,请将您的 HTML 也附加到问题中。
猜你喜欢
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 2019-12-30
相关资源
最近更新 更多