網站搜尋

java - 無法使用 next() 前進


我有一個物件清單,想要在 Spring REST API 中返回,然後在 Angular 中將其讀取為物件陣列:

public Stream<PaymentTransactions> findListByReference_transaction_id(Integer id);

我試了這個:

@GetMapping("/reference_transaction_id/{id}")
public List<ResponseEntity<PaymentTransactionsDTO>> getByListReference_transaction_id(@PathVariable String id) {
    return transactionService
            .findListByReference_transaction_id(Integer.parseInt(id))
            .map(mapper::toDTO)
            .map(ResponseEntity::ok).collect(Collectors.toList());
}

但是當我嘗試將其作為 Angular 陣列來讀取時,我得到 could not advance using next()。從 REST 端點返回列表的正確方法是什麼?

編輯:

@GetMapping("{id}")
    public ResponseEntity<List<ResponseEntity<PaymentTransactionsDTO>>> get(@PathVariable String id) {
        return ResponseEntity.ok(transactionService
                .findListById(Integer.parseInt(id)).stream()
                .map(mapper::toDTO)
                .map(ResponseEntity::ok).collect(Collectors.toList()));

答案#1

修改了你的範例:

@GetMapping("/reference_transaction_id/{id}")
@ResponseBody
public ResponseEntity<List<PaymentTransactionsDTO>> getByListReference_transaction_id(@PathVariable Integer id) {
    try(var stream = transactionService
            .findListByReference_transaction_id(id)){
      var list = stream.map(mapper::toDTO).collect(Collectors.toList());
      return list.isEmpty() ? ResponseEntity.notFound().build() : ResponseEntity.ok(list) 
    }
}
  1. 將 ResponseBody 添加到您的方法中
  2. 使用 try-with-resource 關閉流(我認為你必須關閉它)
  3. 希望它對你有用

關於你的 Angular 問題。如果你能貼一些原始程式碼會有幫助 :)