Angular 11 - Spring Boot - MySQL:POST请求未成功创建数据库条目

Posted

技术标签:

【中文标题】Angular 11 - Spring Boot - MySQL:POST请求未成功创建数据库条目【英文标题】:Angular11 - Spring Boot - MySQL: POST request not successfully creating database entry 【发布时间】:2021-09-20 02:02:24 【问题描述】:

背景

我正在尝试使用 Angular11、Spring Boot 和 mysql 构建票务系统 CRUD 应用程序。

正在成功创建数据库表。我能够查看测试数据并使用 MySQL 或 Postman 手动创建。

我的问题是当我尝试使用简单的表单在数据库中创建一个Ticket条目时,该条目没有成功创建。

我根本没有收到任何错误消息。

我的代码

前端

ticket.ts

export class Ticket 
  id?: number;
  title: string;
  description: string;
  createdOn?: number;
  resolutionDate?: number;

  constructor(title: string, description: string) 
    this.title = title;
    this.description = description;
  

ticket.service.ts

import  HttpClient  from '@angular/common/http';
import  Injectable  from '@angular/core';
import  Observable  from 'rxjs';
import  Ticket  from '../models/Ticket';

@Injectable( providedIn: 'root' )
export class TicketService 
  apiServerUrl = 'http://localhost:8080/tickets';

  constructor(private http: HttpClient) 

  getTickets(): Observable<Ticket[]> 
    return this.http.get<Ticket[]>(this.apiServerUrl);
  

  get(id: number): Observable<Ticket> 
    return this.http.get<Ticket>(`$this.apiServerUrl/$id`);
  

  create(ticket: Ticket) 
    const url = `$this.apiServerUrl/create`;

    console.log(url, ticket);
    return this.http.post<Ticket>(url, ticket);
  

create-ticket.component.ts

import  Component, OnInit  from '@angular/core';
import 
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
 from '@angular/forms';
import  Router  from '@angular/router';
import  Ticket  from 'src/app/models/Ticket';
import  TicketService  from '../../../services/ticket.service';

@Component(
  selector: 'create-ticket',
  templateUrl: './create-ticket.component.html',
  styleUrls: ['./create-ticket.component.css'],
)
export class CreateTicketComponent implements OnInit 
  ticketForm = this.formBuilder.group(
    title: ['', Validators.required],
    description: ['', Validators.required],
  );
  constructor(
    private ticketService: TicketService,
    private router: Router,
    private formBuilder: FormBuilder
  ) 

  ngOnInit(): void 
    let title = new FormControl();
    let description = new FormControl();

    this.ticketForm = new FormGroup(
      title: new FormControl('', Validators.required),
      description: new FormControl('', Validators.required),
    );
  

  public createTicket() 
    const newTicket = new Ticket(
      this.ticketForm.value.title,
      this.ticketForm.value.description
    );

    this.ticketService.create(newTicket);
    this.router.navigate(['/tickets']);
  

  cancel() 
    this.router.navigate(['/tickets']);
  

后端

TicketController.java

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/tickets")
public class TicketController 

    @Autowired
    private TicketRepository ticketRepository;

    ...
    @PostMapping("/create")
        public ResponseEntity<Ticket> createTicket(@RequestBody Ticket ticket) 
            try 
                Ticket _ticket = ticketRepository.save(ticket);
                return new ResponseEntity<>(_ticket, HttpStatus.CREATED);
             catch (Exception e) 
                return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
            
        

我尝试过的

如果我使用 Postman 并使用 JSON 发送 POST 请求,这将成功创建一个数据库条目。

ticket.service.ts 中,return this.http.post&lt;Ticket&gt;(url, ticket); console.log(url, ticket) 的输出是:

【问题讨论】:

【参考方案1】:

这个问题的答案是我的 CreateTicketComponent 没有正确订阅表单中的更改。

新建的CreateTicketComponent如下:

import  Component, OnInit  from '@angular/core';
import  FormBuilder, FormGroup, Validators  from '@angular/forms';
import  Router  from '@angular/router';
import  Ticket  from 'src/app/models/Ticket';
import  TicketService  from '../../../services/ticket.service';

@Component(
  selector: 'create-ticket',
  templateUrl: './create-ticket.component.html',
  styleUrls: ['./create-ticket.component.css'],
)
export class CreateTicketComponent implements OnInit 
  ticketForm: FormGroup;
  ticket: Ticket;

  constructor(
    private ticketService: TicketService,
    private router: Router,
    private formBuilder: FormBuilder
  ) 
    this.ticketForm = this.formBuilder.group(
      title: ['', Validators.required],
      description: ['', Validators.required],
    );
    this.ticket = new Ticket(
      this.ticketForm.value.title,
      this.ticketForm.value.description
    );
  

  ngOnInit(): void 
    this.onValueChanges();
  

  onValueChanges(): void 
    this.ticketForm.valueChanges.subscribe((val) => 
      this.ticket = val;
    );
  

  public createTicket() 
    this.ticketService
      .create(this.ticket)
      .subscribe((result) => this.goToTicketList());
  

  goToTicketList() 
    this.router.navigate(['/tickets']);
  

【讨论】:

以上是关于Angular 11 - Spring Boot - MySQL:POST请求未成功创建数据库条目的主要内容,如果未能解决你的问题,请参考以下文章

Angular - Spring Boot - Keycloak - 401错误

带有 Keycloak 的 Angular/Spring Boot 抛出 403

whitelabel 错误页面 404 spring boot angular 5

spring boot angular csrf令牌握手错误

Spring Boot JWT Cors 不适用于 Angular 8

如何将 Angular 2 与 Spring Boot 应用程序连接起来?