0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AngularとSpring BootでPaginationを実装する

Last updated at Posted at 2021-06-13

概要

1ページに10枚のメモを表示するPaginationを実装します。 Springの標準ライブラリのPageを使うといい感じにPaginationしてくれるので、Angularで適宜デバッグしながらcontentやtotalPagesなどのSpringからのレスポンスがあるのだなと確認・利用していく流れです。

Spring

MemoRepository.java
public interface MemoRepository extends JpaRepository<Memo, Long> {
    Page<Memo> findAll(Pageable pageable);
}
MemoController.java
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class MemoController {
    @Autowired
    MemoRepository memoRepository;

    /**
     * メモをページに応じて取得
     */
    @GetMapping("/{page}")
    public Page<Memo> getMemos(@PathVariable("page") int page) throws IOException {
        //PageRequestはバージョンによって書き方が違うので注意が必要
        return memoRepository.findAll(PageRequest.of(page,10,Sort.by(Sort.Direction.ASC, "id")));
    }
}

Angular

home.component.html
<nav aria-label="Page navigation example">
  <ul class="pagination justify-content-center">
    <li class="page-item"><a class="page-link" (click)="prevMemo()">前へ</a></li>
    <li *ngFor="let in of pageCounter(totalPages) ; let i = index" class="page-item"><a class="page-link" (click)="clickPage(i)">{{i}}</a></li>
    <li class="page-item"><a class="page-link" (click)="nextMemo()">次へ</a></li>
  </ul>
</nav>
home.component.ts
export class HomeComponent implements OnInit {

  memos: Memo[];
  memo: Memo = {
    japanese: '',
  };
  totalPages: number = 0;
  currentPage: number = 0;

  constructor(private service: MemoService){}

  /**
   * 初期表示時、メモを取得。デフォルトは0ページ。
   */
  ngOnInit(): void {
    this.getMemos(this.currentPage);
  }

  /**
   * メモ取得。
   */
  getMemos(page: number) {
    this.service.getMemos(this.currentPage).subscribe(data => {
      this.memos = data.content;
      this.totalPages = data.totalPages;
    });
  }

  /**
   * 「前へ」押下時、1ページ後ろのページに応じてメモを取得。
   */
  prevMemo(){
    if(this.currentPage !== 0){
      this.currentPage = this.currentPage -1;
      this.getMemos(this.currentPage);
    }
  }

  /**
   * 「次へ」押下時、1ページ先のページに応じてメモを取得。
   */
  nextMemo(){
    if(this.currentPage !== this.totalPages -1){
      this.currentPage = this.currentPage +1;
      this.getMemos(this.currentPage);
    }
  }

  /**
   * ページ押下時、ページに応じてメモを取得。
   */
  clickPage(i: number){
    this.currentPage = i;
    this.getMemos(this.currentPage);
  }

  /**
   * ページ件数を動的に表示する。
   */
  pageCounter(i: number){
    return new Array(i);
  }

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?