Creating paginations in Angular using the Movie DB API

I'm an aspiring developer looking to enhance my application by integrating the tmDB API. However, I am facing challenges as a newcomer and need guidance on how to add more pages.

Within my movie component, I have a Movie Service that includes the following method:

  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);
  }

While this code currently displays the first 20 movies on the page, I wish to implement pagination so that users can navigate to subsequent pages seamlessly. Unfortunately, I am unsure how to update the value of ${page} in movies.service.ts (discoverMovies) or in the HTML file.

To demonstrate how I achieved displaying 20 movies on my page:

In 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);
    }
  }

In 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;
    });
  }

In 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">
          Release Date: {{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">Details</a>
      </div>
    </div>
  </div>
</div>

At this point, I aim to dynamically modify the value of ${page} in movies.service.ts by clicking on buttons:

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

Answer №1

To add a currentPage property to your component class, simply declare it like this:

public currentPage:number = 1;

Whenever you click on the button, make sure to invoke the getMovies() function with the parameter currentPage+1, and remember to update the value of currentPage accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of Three.js and OrbitControls in TypeScript

I am struggling to implement this example using TypeScript. I have included <script src="lib/three.min.js"></script> and <script src="lib/OrbitControls.js"></script> in the <head> of my html file, and the TypeScript file in t ...

In Typescript 2.2, when using Express, the request and response objects are implicitly

I'm facing some challenges when it comes to incorporating types into my node/express project. Currently, I am using TypeScript 2.2 and express 4.x with the following npm installation for types: npm install --save-dev @types/express import * as expr ...

Tips for collapsing or expanding a single button in Angular 6

I want to create rows of collapsible buttons in my code, but every time I visit the page, all the buttons are already expanded. Additionally, when I click on any button, they all expand or collapse simultaneously. HTML <div id="accordion" *ngFor="let ...

Retrieve the user information from Auth0 within the NestJS application

I am currently working on implementing Auth0 authorization in NestJS, but I am unsure of how to retrieve the user's data within the callback URL handler. In a normal express function, this issue could be resolved using the following code. The passpor ...

Having trouble loading image on web application

Currently, I am facing an issue while attempting to add a background image to an element within my Angular web application. Strangely enough, the relative path leading to the image seems to be causing my entire app to break. https://i.stack.imgur.com/b9qJ ...

I'm having trouble retrieving the value from the textbox in my Angular 7 project using TypeScript

I'm currently working with Angular 7 and trying to create a textbox to display its value in an alert. However, I'm facing difficulty in fetching the textbox value in typescript. I would appreciate any guidance on how to proceed with this issue. ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Collada integration with Angular using Three.js

Requesting assistance to develop a webapp using Angular4 with THREEjs for viewing Collada Objects, but encountering challenges. UPDATE: Seeking a working example or helpful hints as efforts in researching and exploring code with other loaders have prove ...

What is the best way to compress a file for transfer to a server using gzip?

While attempting to upload a file and send it to the server via a REST API, I am looking for a reliable method to gzip the file. Unfortunately, there is limited documentation available on this topic. Can anyone suggest the most effective approach to achiev ...

Steps for linking HTTP requests in Angular 2 depending on the type of response

My attempt to create an api call from a remote server and then, if an error occurs, make another request from my local server is not working as expected. I am encountering errors and need help to determine if my approach is feasible. Here is the code snip ...

Understanding how to extract an enum from a string and its corresponding value in TypeScript

I am working with a simple enum called errorCode, shown below: export enum SomeErrorCodes { none = 0, notFound = 1, duplicated = 2 } Currently, I am receiving the name of the enum as a string "SomeErrorCodes" and a number, for example, 1. How ...

StatusChanges retrieves the previous status prior to the execution of AsyncValidators

When checking for errors using statusChanges, I display the resulting array of errors in the html template. To validate input asynchronously, I utilize an asynchronous validator. The sequence of events is as follows: Upon entering text or losing focus in t ...

Generating a Typescript type based on Enum values

Is there a more efficient way to generate a Typescript type based on ENUM values? Currently, I find myself manually creating the type and ensuring it stays synchronized with the ENUM. Can a type be automatically generated from ENUM values in such a way th ...

Issue with updating view in React Native/Javascript after an asynchronous fetch operation. Execution order may be invalid

Below is the code I've written to fetch data using fetch() and display an output only after fetching it. However, the view fails to update after the asynchronous call. Since I'm new to react native async calls, I would appreciate some help on thi ...

Tips for conducting tests on ngrx/effects using Jasmine and Karma with Angular 5 and ngrx 5

Here is the file that I need to test. My current focus is on some effects service while working with Angular5 (^5.2.0) and ngrx5 (^5.2.0). I have been struggling to properly implement the code below for testing purposes. Any tips or suggestions would be ...

Recommendations for Configuring VPS for Angular2 and .Net Application

My team and I are currently in the process of developing an application that combines Angular2 for the front-end and Web API ASP.NET for the back-end. We are currently at the stage of configuring a VPS for this application but unfortunately, we lack the ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

Angular: Converting the outcome of a request to an observable

When working on my project, I decided to tackle it module by module to ensure each part had access to the user. However, as I refine the project, I'm encountering a situation where multiple API requests are being made for the same purpose (user info) ...

Difficulty encountered while configuring ngx-lightbox within an Angular module

Greetings! I am relatively new to working with Angular and currently in the process of creating a website that requires lightbox galleries within each component. Upon seeking advice, ngx-lightbox was recommended as a solution for my photo gallery needs. Ho ...

Enhance Vue TypeScript components with custom component-level properties

In my vue2 project, I am utilizing vue-class-component along with vue-property-decorator. My goal is to implement component-level security validation for each component when it loads. I imagine implementing it with a signature like this: @Component @Secur ...