如何在angular 6中显示spring引导数据jpa查询的响应

lp0sw83n  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(315)

我之前的问题spring boot data jpa-如何在spring boot应用程序中获取特定id的数据我有这样一个问题:

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,一切正常,我得到了这样一个结果:

我想用Angular6在我的web应用程序中显示这个结果
机票.ts

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

机票服务.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;
});}}

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

n3ipq98p

n3ipq98p1#

好的,我已经用 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);

相关问题