首页 > 解决方案 > 如何在 Angular 6 中显示 Spring Boot Data JPA Query 的响应

问题描述

我之前的问题Spring Boot Data JPA - how to get data for the certain id是连续的 在我的 Spring Boot 应用程序中,我有这样一个查询:

public interface FlightTicketRepository extends JpaRepository<Ticket, Integer> {

@Query("SELECT new dto.FlightTicketDto(t.ticket_id, f.departureDate, f.destinationDate, t.name, t.surname) "
        + "FROM Flight f INNER JOIN f.tickets t where t.ticket_id = :ticket_id")
List<FlightTicketDto> findByTicketId(Integer ticket_id);}

还有这样的控制器

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class FlightTicketController {

@Autowired
FlightTicketRepository flightTicketRepository;

@GetMapping("/mytickets/{ticket_id}")
public List fetchEmpDeptDataInnerJoin(@PathVariable Integer ticket_id) {
    return flightTicketRepository.findByTicketId(ticket_id);
}}

使用我的@Query 一切正常,我得到了这样的结果:

在此处输入图像描述

我想使用 Angular 6 在我的 Web 应用程序中显示这个结果

FlightTicket.ts

export class FlightTicket {
 ticket_id: number;
 departureDate: Date;
 destinationDate: Date;
 name: string;
 surname: string;
}

FlightTicketService.ts

 export class FlightTicketService {

 private baseUrl = 'http://localhost:8080/api/mytickets';

 constructor(private http: HttpClient) {
 }

 fetchEmpDeptDataInnerJoin(ticket_id: number): Observable<FlightTicket> {
 return this.http.get<FlightTicket>(`${this.baseUrl}/${ticket_id}`);
 }

mytickets-list.component.html - 在这里我想显示我的查询响应

<div *ngIf="flightTicket">
<label>Destination date: </label> {{ flightTicket.destinationDate }}<br/>
<label>Departure date: </label> {{ flightTicket.departureDate }}<br/>
<label>Name: </label> {{ flightTicket.name }}<br/>
<label>Surname: </label> {{ flightTicket.surname }}<br/>
<label>id: </label> {{ flightTicket.ticket_id }}<br/>

myticketslist-component.ts

export class MyticketsListComponent implements OnInit {

 flightTicket: FlightTicket = new FlightTicket( );
 flightTickets: Observable<FlightTicket[]>;
 ticket_id: number;

 constructor(private flightTicketService: FlightTicketService) { }

 ngOnInit() {
 this.ticket_id = 443;
 this.reloadData();
 }

reloadData() {
this.flightTicketService.fetchEmpDeptDataInnerJoin(this.ticket_id).
subscribe((response) => {
  this.flightTicket = response;
});}}

这是结果。空的。怎么了?

在此处输入图像描述

标签: mysqlangularspring-boot

解决方案


好的,我已经调试使用Augury并发现我的 json 响应就像一个数组,而不是一个对象(应该是这样)

所以我改变了我的后端:

@GetMapping("/mytickets/{ticket_id}")
public ResponseEntity<FlightTicketDto> fetchEmpDeptDataInnerJoin(@PathVariable("ticket_id") Integer ticket_id) {
    FlightTicketDto flight = flightTicketRepository.findByTicketId(ticket_id);
    return new ResponseEntity<>(flight, HttpStatus.OK);
}

和这里:

@Query("SELECT new dto.FlightTicketDto(t.ticket_id, f.departureDate, f.destinationDate, t.name, t.surname) "
        + "FROM Flight f INNER JOIN f.tickets t where t.ticket_id = :ticket_id")
FlightTicketDto findByTicketId(Integer ticket_id);

推荐阅读