You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用GET接口获取问题渲染到Material表单问题排查

Angular问题修复方案

1 TypeScript端问题与修复

存在的问题

  • 你没有给data变量声明正确的类型,TS默认推断为never[],所以赋值时会提示属性不存在的错误
  • 注释行里写的this.results.data是无效变量,接口返回的结果保存在回调参数res中,应该取res.data
  • getAllQuestion()是异步方法,数据在subscribe的回调中返回,方法本身没有返回值,你在ngOnInit里直接this.data = this.getAllQuestion()属于无效赋值

修复代码

首先在组件类中声明data的类型:

// 可选:先定义问题的类型结构,方便类型校验
interface Question {
  id: number;
  questionId: string;
  question: string;
  companyId: string;
}

// 组件类中声明data变量
data: Question[] = [];

然后修改业务逻辑代码:

ngOnInit(): void {
  // 直接调用请求方法,异步回调内给data赋值
  this.getAllQuestion();
}

getAllQuestion() {
  this.user.getAllQuestions().subscribe((res: any) => {
    // 用回调返回的res获取数据赋值
    this.data = res.data;
    console.log(res);
  })
}

如果需要用响应式表单管理所有问题的回答,需要额外初始化FormArray:

// 提前导入ReactiveFormsModule相关依赖
questionForm: FormGroup = this.fb.group({
  answers: this.fb.array([])
});

get answers() {
  return this.questionForm.get('answers') as FormArray;
}

// 拿到接口返回的data后初始化表单控件
this.data.forEach(() => {
  this.answers.push(this.fb.control(''));
})

2 HTML端问题与修复

存在的问题

  • *ngFor写在<mat-label>上会生成多个标签对应同一个输入框,不符合每个问题对应一个回答输入框的需求
  • 所有输入框共用同一个formControlName="question"会导致表单数据覆盖

修复代码示例

使用FormArray的场景写法:

<form [formGroup]="questionForm">
  <mat-form-field 
    appearance="fill" 
    class="example-full-width"
    *ngFor="let item of data; let i = index"
  >
    <mat-label>{{item.question}}</mat-label>
    <textarea matInput formControlName="i"></textarea>
  </mat-form-field>
</form>

如果不需要响应式表单能力,也可以直接用ngModel绑定值:

<mat-form-field 
  appearance="fill" 
  class="example-full-width"
  *ngFor="let item of data"
>
  <mat-label>{{item.question}}</mat-label>
  <textarea matInput [(ngModel)]="item.answer" [ngModelOptions]="{standalone: true}"></textarea>
</mat-form-field>

内容的提问来源于stack exchange,提问作者Sahana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:06:03