简体   繁体   English

Angular 9 将 json 响应映射到数组

[英]Angular 9 mapping a json response to array

I have this interface我有这个界面

export interface Student {
    cf: string,
    firstName: string,
    lastName: string,
    dateOfBirth: Date,
    description?: string,
    enrollmentDate?: Date
}

I want to populate an array of students with a http get request , which returns the following json for each student我想用http get request填充一组学生,它为每个学生返回以下 json

{cf: "blablabla", first_name: "Mario", last_name: "Rossi", date_of_birth: "1998-01-24", enrollment_date: "2019-03-20" },

As you can see, the interface has different names from the response ( firstName instead of first_name ), so when I print to the console the names of the students I get undefined .如您所见,该接口的名称与响应不同( firstName而不是first_name ),因此当我将学生的姓名打印到控制台时,我得到undefined

This is the service function from which I get the data这是我从中获取数据的服务 function

  getStudents(): Observable<Student[]> {
    return this.httpClient.get<Student[]>(this.studentsUrl, this.baseService.httpOptions);
  }

And here is my students component这是我的学生组件

export class StudentsComponent implements OnInit {

  students: Student[];
  childIcon = faChild;
  plusIcon = faPlus;
  private _newStudent: boolean = false;

  constructor(private studentsService: StudentsService) { }

  ngOnInit(): void {
    this.studentsService.getStudents().subscribe(
      (result: Student[]) => {
        this.students = result;
        this.students.forEach(student => console.log(student));
      },
      error => console.log(error)
    )
  }
}

Is there a way to convert the json response to my Student interface?有没有办法将 json 响应转换为我的学生界面? Several answers on stack overflow suggest map is the way, but I don't understand how to use that operator alog with subscribe关于堆栈溢出的几个答案表明map是这种方式,但我不明白如何使用该运算符和订阅

One way would be manually loop through the array and define new keys and delete obsolete ones before returning the array using RxJS map .一种方法是手动循环遍历数组并定义新键并删除过时的键,然后使用 RxJS map返回数组。

Service服务

import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';

getStudents(): Observable<Student[]> {
  return this.httpClient.get<Student[]>(this.studentsUrl, this.baseService.httpOptions).pipe(
    map(response => response.forEach(student => {
        student.firstName = student.first_name;
        student.lastName = student.last_name;
        student.dateOfBirth = student.date_of_birth;
        student.enrollmentDate = student.enrollment_date;
        delete student.first_name;
        delete student.last_name;
        delete student.date_of_birth;
        delete student.enrollment_date;
      });
    )
  );
}

But depending on the number of elements in the array, this could be a heavily taxing operation for a single HTTP request.但是根据数组中元素的数量,对于单个 HTTP 请求来说,这可能是一项繁重的操作。 Couldn't you define the interface definition to match the one of the API?您不能定义接口定义以匹配 API 之一吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM