Search code examples
angulartypescriptthemoviedb-api

Making paginations with Angular - The Movie DB API


I'm trying to add more pages on my aplication consuming tmDB API, but I'm newbie and I don't know how to do it.

I have in my movie component a Service of movies

  discoverMovies(page: number) {
    let discover = `${this.discoverUrl}?api_key=${this.apiKey}&language=${this.language}&sort_by=popularity.desc&include_adult=false&include_video=false&page=${page}`;
    return this.http.get(discover);
  }

This code shows the first 20 movies on my page, but I want a pagination to show more movies when I skip to the next page and I don't know how to change the ${page} value on movies.service.ts (discoverMovies) or in the HTML

Let me show how I made to show 20 movies on my page:

movies.service.ts:

getMovies(query: string = '', page: number = 1) {
    
    if ((query = '')) {
      return this.discoverMovies(page);
    }
    if (query) {
      return this.searchMovies(query, page);
    } else {
      return this.discoverMovies(page);
    }
  }

movies.component.ts:

  getMovies() {
    this.moviesService.getMovies(this.movieName).subscribe((paramName) => {
      this.actualPage = (paramName as any).page;
      this.totalPages = (paramName as any).total_pages;
      this.movies = (paramName as any).results;
    });
  }

movies.component.html:

<div class="row">
  <div *ngFor="let movie of movies" class="col-sm-4">
    <div class="card">
      <div class="card-body">
        <h4 class="card-title" style="text-align: center;">{{movie.title}}</h4>
        <hr>
        <img *ngIf="movie.poster_path" [src]="getImage(movie.poster_path)" class="posterPath">
        <img *ngIf="!movie.poster_path" class="posterPath" src="https://placehold.it/500x740">
        <div class="movies-info">
          Data de Lançamento: {{movie.release_date}} <span><img src="https://www.kindpng.com/picc/b/29/298871.png"
              alt="logo-star">{{movie.vote_average}}</span>
        </div>
        <p class="card-text" style="text-align: center;">{{movie.overview}}</p>
        <a class="btn btn-primary" id="movie-details">Detalhes</a>
      </div>
    </div>
  </div>
</div>

Here is the place I want to change the value of ${page} of movies.service.ts clicking on the buttons:

<div class="pagination">
  <button class="btn btn-primary">-</button>
  <input type="text" [value]="actualPage" readonly>
  <button class="btn btn-primary">+</button>
</div>

Solution

  • Create a currentPage property in your component class

    public currentPage:number = 1;
    

    And whenever you click on the button, call the getMovies() function with currentPage+1 parameter, and don't forgot to update the value of currentPage.