如何在Angular中展示Laravel API一对多关联的薪资数据
解决Angular展示Laravel关联模型Salary数据的问题
问题根源
从你提供的JSON输出可以看到,薪资数据存储在employee.salaries数组中(因为Laravel的一对多关联会以数组形式返回关联数据),但你的Angular模板错误地直接访问了employee.salary、employee.from_date这类不存在的属性,同时没有处理异步数据加载前的空值场景。
具体修复步骤
1. 修正Angular模板,正确遍历薪资数组
修改HTML模板,使用*ngFor遍历salaries数组,同时通过安全导航操作符?避免数据加载完成前的空指针错误:
<div class="basic-info"> <p>Employee Name : {{ employee?.first_name }} {{ employee?.last_name }}</p> <p>Date of Birth : {{ employee?.birth_date }}</p> <p>Gender : {{ employee?.gender }}</p> <p>Hire Date : {{ employee?.hire_date }}</p> </div> <div class="salary-topic"> <h4><b>Salary Details</b></h4> </div> <div class="salary-details"> <table class="table"> <thead> <tr> <th scope="col">Salary</th> <th scope="col">From Date</th> <th scope="col">To Date</th> </tr> </thead> <tbody> <!-- 遍历salaries数组,渲染每条薪资记录 --> <tr *ngFor="let salary of employee?.salaries"> <td>{{ salary.salary }}</td> <td>{{ salary.from_date }}</td> <td>{{ salary.to_date }}</td> </tr> </tbody> </table> </div>
2. 可选:添加TypeScript类型定义(增强代码健壮性)
在employee-by-id.ts中定义接口,让编辑器提供属性提示并避免类型错误:
// 定义薪资数据接口 interface Salary { emp_no: number; salary: number; from_date: string; to_date: string; created_at: string; updated_at: string; } // 定义员工数据接口 interface Employee { emp_no: number; birth_date: string; first_name: string; last_name: string; gender: string; hire_date: string; created_at: string | null; updated_at: string | null; salaries: Salary[]; } // 声明employee变量类型 employee: Employee | undefined;
3. 优化Laravel控制器代码(避免重复查询)
你的控制器中重复执行了关联查询,可以简化为:
public function getEmployeeById($id) { $employee = Employee::with('titles','salaries')->find($id); if(is_null($employee)) { return response()->json(['message' => 'Employee Not Found'], 404); } return response()->json($employee, 200); }
效果说明
修改完成后,Angular会正确遍历salaries数组展示所有薪资记录,安全导航操作符?会确保在API数据返回前不会抛出空值错误,同时Laravel端的代码也避免了不必要的重复数据库查询。
内容的提问来源于stack exchange,提问作者Narakaya
相关产品推荐
相关产品推荐

