首页 > 解决方案 > 如何在 Angular 中使用和导出我的类中的对象数组

问题描述

我正在使用 Spring boot 和 Angular 设置一个应用程序来研究前端。我有一些 REST API 为我提供学生对象和班级对象。如何正确声明这些对象和数组以及如何将它们发布回我的 Spring 应用程序?

到目前为止我所拥有的:

我在后端填充的 localhost:8080/api/students/ 的 API 正在返回:

[
    {
        "id": 8,
        "name": "john",
        "classes": [
            {
                "id": 1,
                "name": "math"
            },
            {
                "id": 2,
                "name": "english"
            }
        ]
    },
    {
        "id": 9,
        "name": "paul",
        "classes": [
            {
                "id": 1,
                "name": "math"
            },
            {
                "id": 3,
                "name": "science"
            }
        ]

    }
]

我在后端填充的 localhost:8080/api/classes/ 的 API 正在返回:

[
    {
        "id": 1,
        "name": "math"
    },
    {
        "id": 2,
        "name": "english"
    },
    {
        "id": 3,
        "name": "science"
    }
]

这是我的前端

学生.ts

import { Classes} from "./classes";

export class Student{
    id: number;
    name: string;
    classes: Classes[];
}

我是否将课程声明为学生内部的数组?

类.ts

export class Classes{
    id: number;
    name: string;
}

创建-form.component.html

<h3>Create Student</h3>
<div [hidden]="submitted" style="width: 400px;">
  <form (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="name">Name</label>
      <input type="text" class="form-control" id="name" required [(ngModel)]="student.name" name="name">
    </div>    
    <div class="form-group">
      <label for="classes">Classes</label>
      <select class="form-control" id="classes" name="classes" required [(ngModel)]="student.classes">
        <option *ngFor="let class of classes | async"> {{ class.name }}</option>
      </select>
    </div> 
    <button type="submit" class="btn btn-success">Submit</button>
  </form>
</div>

创建-form.component.ts

student: Student= new Student();
classes: Observable<Classes[]>;
submitted = false;
constructor(private studentService: StudentService) { }
ngOnInit() {
    this.classes= this.studentService.getClassesList();
}
onSubmit() {
    this.submitted = true;
    this.save();
}
save() {
    this.studentService.createStudent(this.student)
      .subscribe(data => console.log(data), error => console.log(error));
    this.student= new Student();
}

我可以在选择中显示类列表,但是在选择一个并提交后我得到

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: "http://localhost:8080/api/students/create", ok: false, …}
error:
error: "Bad Request"
message: "JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of VALUE_STRING token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of VALUE_STRING token ...
path: "/api/students/create"
status: 400

有人可以帮助我并解释我做错了什么吗?此外,还有其他选项可以在表单中选择多个类吗?目前只能选择一个!


更新@ashish.gd 的答案 这是当我在类中没有 ngmodel 绑定的情况下发布时我的网络选项卡的预览

{id: 8, name: "johnny", classes: null"}
id: 8
classes: null
name: "johnny"

这是我的网络标签的标题

Request URL: http://localhost:8080/api/students/create
Request Method: POST
Status Code: 200 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: http://localhost:4200
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/json
Origin: http://localhost:4200
Referer: http://localhost:4200/add

标签: angularspring-boot

解决方案


selecthtml 元素将选定的值绑定到该值,student.classes该值基本上是一个简单的字符串。因此,您的请求对象将使用类作为字符串创建。例如:

{
    id: 8,
    name: "johnny",
    classes: "science"
}

您的 API 端点期望classes属性是列表或数组。

因此JSON parse error: Cannot deserialize instance of java.util.ArrayList out of VALUE_STRING token;

更改您的请求对象以将classes属性作为数组传递应该可以解决您的错误。例子:

{
    id: 8,
    name: "johnny",
    classes: ["science"]
}

但是,通过简单的绑定无法将选定的项目推入数组。在组件中创建 api 之前,您需要将classes属性从字符串转换为数组。


推荐阅读