Angular Api 请求与 id 上其他模型有关系的模型

问题描述 投票:0回答:1

假设我有如下所示的对象:

Students = [
  {
    id: 1,
    name: "Sara",
    schoolId: 1,
    carId: 3,
  },
  {
    id: 2,
    ...
  },
]

School = [
  {
    id: 1,
    name: "Some college",
    location: "Somewhere",
  },
  {
    id: 2,
    ...
  },
]

Car = [
  {
    id: 3,
    make: "",
    model: ""
  }
]

API服务:

  getStudents() {
    return this.http.get<Student[]>(this.studentUrl);
  }

如果我像上面那样向 Student 发出 get 请求,我只会获得“schoolId”和“carId”的 id。将这两个属性链接到其他两个对象列表中的实际对象的正确方法是什么,以便 getStudents() 的结果将返回如下所示的内容并能够在 html 上调用“student.schoolId.name”?

   {
    id: 1,
    name: "Sara",
    schoolId: {
      id: 1,
      name: "Some college",
      location: "Somewhere",
    },
    carId: {
      id: 3,
      make: "",
      model: ""
    }
  }

我研究过地图和平面图,但我不确定这是否是正确的选择。我将这些对象基于数据库数据将发送的内容。 “schoolId”和“carId”列包含的 ID 仅用于链接学校和汽车表中的 ID。

angular http model normalization
1个回答
0
投票

您可以在后端服务中返回评论中提到的具有关联实体的数据,也可以使用

forkJoin
发送响应以获取多个数据。待观察量完成后,使用
map
来转换数据,如下所示:

export interface Student {
  id: number;
  name: string;
  schoolId: number;
  carId: number;
}

export interface School {
  id: number;
  name: string;
  location: string;
}

export interface Car {
  id: number;
  make: string;
  model: string;
}

export interface StudentWithSchoolCarData extends Student {
  school: School;
  car: Car;
}
getStudentsWithSchoolCarData(): Observable<StudentWithSchoolCarData[]> {
  return forkJoin([
    this.http.get<Student[]>(this.studentUrl),
    this.http.get<School[]>(this.schoolUrl),
    this.http.get<Car[]>(this.carUrl),
  ]).pipe(
    map(([students, schools, cars]: any[]) => {
      return students.map((x: Student) => ({
        ...x,
        school: schools.find((y: School) => y.id == x.schoolId),
        car: cars.find((y: Car) => y.id == x.carId),
      }));
    })
  );
}

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.