API返回值无法赋值表单:如何正确访问对象属性
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

