如何通过Angular中的JSON响应在formArray中添加数据?

问题描述

我有一个来自firebase的JSON响应,但是当我加载页面时,它仅显示formArray中的第一个数组,而不显示多个字段。请检查下面的代码,并指导我哪里做错了。

这是我的回复来自firebase的快照。

enter image description here

代码

 ngOnInit(): void {
    this.loadForm();
    this.questionService.getQuestion(this.id).subscribe((res) => {
      this.editQuestionForm.patchValue({
        question: res.payload.data()['question'],type: res.payload.data()['type'],next_question: res.payload.data()['next_question'],actions: res.payload.data()['actions'],});
    });
   }

  loadForm() {
    this.editQuestionForm = this.fb.group({
      question: ['',Validators.required],type: ['',actions: this.fb.array([this.createActionFields()]),next_question: ['',});
  }

  action_fields(): FormArray {
    return this.editQuestionForm.get('actions') as FormArray;
  }

  createActionFields(): FormGroup {
    return this.fb.group({
      field: '',response: '',});
  }

  addActionFields() {
    this.action_fields().push(this.createActionFields());
  }

  removeActionFields(index) {
    this.action_fields().removeAt(index);
  }

这是输出结果

enter image description here

请检查我上面的代码并指导我,我该怎么做才能显示正确的数据。

解决方法

如果动作响应,则需要在动作中具有与响应动作大小相同的控件。

例如,如果由于使用addActionFields()而需要patchValue五次的5个字段的响应返回数组,则不会出现错误,但是如果您使用setValue,则会看到错误。

this.questionService.getQuestion(this.id).subscribe((res) => {
    const actions = res.payload.data()['actions'];
    action.forEach( () =>{
      this.addActionFields();
    });

   this.editQuestionForm.patchValue({
     question: res.payload.data()['question'],type: res.payload.data()['type'],next_question: res.payload.data()['next_question'],actions
   });
 });