【问题标题】:Sending an object from Angular8 to Spring Boot将对象从 Angular8 发送到 Spring Boot
【发布时间】:2020-02-01 16:34:01
【问题描述】:

我对 Web 开发还很陌生,我承认遵循一些在线指南后,我对一些基本概念仍然有些困惑。 我有一个运行良好的 Angular8 表单:我插入数据并点击“提交”。

onSubmit() {
    console.log(this.model);
    this.submitted = true;
  }

并在控制台打印表单的数据(我关注this official guide供参考)。

这是我的search-message.tsmodel的类)的内容:

export class SearchMessage {

  constructor(
    public id: number,
    public inputText: string,
    public targetSite: string,
    public searchLimit: number,
    public details: boolean
  ) { }
}

现在我正在尝试编写一个 Spring Boot 应用程序,它将接收model 对象,我将简单地打印输出相同的数据。此过程不应涉及数据库(这就是我感到困惑的原因:我在网上找到的所有指南都是关于将服务器上的数据库连接到 Angular 中的视图)。我该怎么做?

【问题讨论】:

  • 您好,您可以添加您在 Angular 中使用的模型类吗?
  • 感谢@A.Wolf 的评论。我刚加了!

标签: angular spring-boot web-development-server


【解决方案1】:

在 Spring Boot 中,您必须定义一个控制器类,该类公开一个您将从 Angular 应用程序调用的端点。

@RestController
@RequestMapping("/path")
public CustomController {
    @PostMapping("message")
    public ResponseEntity<?> addModel(@RequestBody SearchMessage message) {

        // do what you need with the element (ex. write to a db, print data..)
        System.out.println("Data received: " + message.toString());

        return ResponseEntity.ok().build();

    }
}

SearchMessage 应该是这样的:

class SearchMessage {
    private int id; 
    private String inputText;
    private String targetSite;
    private int searchLimit;
    private boolean details;

    // getters and setters
}

并且,假设后端应用程序在端口8081 上运行,您可以像这样向端点发布:

http://localhost:8081/your-app-context-path/path/message

主体必须与您在方法参数message 中定义的SearchMessage 类兼容。
请注意,您可以在 application.properties 文件中添加此属性来定义应用程序的上下文路径:

server.servlet.context-path=/myCoolApp

您可以在Spring example 中找到完整的工作示例。另请参阅this more complete article
如果您需要更多详细信息或解释,请告诉我。

【讨论】:

  • 再次感谢。当你说“body 必须与 SearchMessage 类兼容的地方”时,你是什么意思?
  • 欢迎您!只是后端的SearchMessage类的字段必须与前端的SearchMessage类的字段兼容,即数字字段在后端应该变成整数或浮点数字段并且必须具有相同的名称.显而易见的事情,但如果它们有不同的类型或名称,那么从前端传递到后端对象的内容的编组将失败。
  • 我还添加了SearchMessage 类。
  • 如果答案帮助您解决了问题,请考虑接受:)
  • 我几乎设法解决了这个问题。无论如何,您的回答真的很有帮助,所以无论如何我都会接受它:) 我还有几个(也许是微不足道的)问题:所以我必须在两个不同的端口上同时运行这两个应用程序,对吗? Angular 中的 POST 会如何?
猜你喜欢
  • 1970-01-01
  • 2022-12-02
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2017-02-09
  • 2018-03-05
相关资源
最近更新 更多