【问题标题】:Unable to fetch for each value of undefined in angular无法获取角度中未定义的每个值
【发布时间】:2020-07-08 15:04:22
【问题描述】:

我想从 API 获取数组的数组到表单中,但也无法更新该数据。

我试试这个方法。 从 API 中获取一个值并作为补丁值插入到表单中,并希望迭代以形成一个数组。

 this.quizForm.patchValue({
        name: name,
        order: this.position,
        type: type,
        path: null,
        quizTime: quizTime,
        quizInstruction: quizInstruction,
        questionList:questionList.forEach(element => {
          console.log(element);  
        })
      })

收到数据错误:-

当我从 API 获取数据时,它只显示表单中数组的第一个对象。控制台.log(问题列表); console.log(this.quizForm.value.questionList);

回复:-

测验形式:-

 createQuizForm() {
    this.quizForm = this.fb.group({
      name: ['', Validators.required],
      type: ['quiz'],
      path: [null],
      order: this.position,
      quizTime: ['', [Validators.required, Validators.pattern('^[1-9][0-9]*$')]],
      quizInstruction: ['', Validators.required],
      questionList: this.fb.array([this.initQuestions()]),

    })
  }

  initQuestions(): FormGroup {
    return this.fb.group({
      questionText: ['', Validators.required],
      optionList: this.fb.array([this.initOptions()])
    })
  }

  initOptions(): FormGroup {
    return this.fb.group({
      optionText: ['', Validators.required],
      isAnswer: ['true', Validators.required]
    })
  }

【问题讨论】:

  • 你为什么要尝试遍历“已修补”问题列表?
  • 正如@Batajus 所说,您不需要迭代。只需将获取的列表分配给您的数组
  • 你可以在这里添加你的回复
  • 当我从 API 获取数据时,它只显示表单中数组的第一个对象。
  • 请参考更新

标签: angular typescript angular8


【解决方案1】:

forEach 如果应用它的属性未定义,则会抛出错误。

只需进行以下更改,

this.quizForm.patchValue({
        name: name,
        order: this.position,
        type: type,
        path: null,
        quizTime: quizTime,
        quizInstruction: quizInstruction,
        questionList: questionList?.forEach(element => {  // ? is added (assuming that you are working on typescript
          console.log(element);  
        })
      })

【讨论】:

  • 在打字稿中'?'是否允许进行空检查?
  • 是的。这是允许的。如果您的代码不支持,请检查打字稿版本。
【解决方案2】:

通过下面的代码,我的问题解决了 --

 const question = this.quizForm.get('questionList') as FormArray;

      question.clear();
      questionList.forEach(element => {
        question.push(
          this.fb.group({
            id:element.id,
            questionText:element.questionText,
            optionList:this.setOptions(element)
          })
        )
      });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多