Angular 9将json响应映射到数组

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

我有这个界面

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

我想用http get request填充学生数组,该数组为每个学生返回以下json

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

如您所见,界面的名称与响应的名称不同(firstName而不是first_name),因此,当我在控制台上打印学生的姓名时,会得到undefined

这是我从中获取数据的服务功能

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

这是我的学生部分

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)
    )
  }
}

是否可以将json响应转换为我的Student界面?关于堆栈溢出的几个答案表明map是这样的,但是我不明白如何在subscribe

中使用该运算符alog
json angular mapping response angular-arrays
1个回答
1
投票

一种方法是手动循环遍历数组并定义新键,并在使用RxJS map返回数组之前删除过时的键。

服务

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;
      });
    )
  );
}

但是根据数组中元素的数量,这可能是单个HTTP请求的繁重工作。您是否不能定义接口定义以匹配其中一种API?

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