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

API返回值无法赋值表单:如何正确访问对象属性

Fix: Cannot Access API Response Properties (Getting undefined)

Hey there! I can spot the issue right away from your console output. Let's break it down:

The Root Cause

Your console.log(res) shows:

0: {destination: "test@test.com", domain_id: 2, id: 5, source: "tester0700@test.com", __proto__: Object}

This means res is actually an array containing a single student object at index 0, not a standalone object. When you try to access res.domain_id, you're looking for a property directly on the array (which doesn't exist), hence the undefined.

The Solution

You need to extract the first element from the array first, then access its properties. Here's the corrected code:

this.studentApi.GetStudent(id).subscribe((res) => {
  console.log(res);
  // Grab the first student object from the response array
  const student = res[0];
  
  console.log('student data is: ' + student.domain_id);
  this.subjectArray = res; // Keep this if you need the full array elsewhere
  
  // Now use the extracted object to build your form
  this.studentForm = this.fb.group({
    id: [student.id],
    domain_id: [student.domain_id],
    source: [student.source],
    destination: [student.destination]
  });
});

Bonus Check

If your API is supposed to return a single student object (not an array), you might want to follow up with your backend team to confirm the response format. But the code above will fix the frontend issue immediately.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:23:43