Data exchange between components via an API

I'm in the process of developing a website dedicated to showcasing the top 20 highest-rated Sci-fi movies. The main component on the homepage utilizes a GET request through a service to retrieve an array of objects containing the movie data. This movie data is then displayed using ngFor* in its HTML template.

Each movie thumbnail on the homepage has a click event handler that directs users to a separate page where more detailed information about the selected movie, such as description and ratings, will be displayed. To achieve this functionality, I am utilizing a service that makes another GET request, with the selected movie's id being passed as a parameter in the query.

Below is the code snippet for the Homepage component responsible for rendering the initial API movie data:


import { Component } from '@angular/core';
import { MovieDataService } from '../services/movie-data.service';

@Component({
  selector: 'home-card',
  templateUrl: './home-card.component.html',
  styleUrls: ['./home-card.component.css']
})
export class HomeCardComponent {

  movieData: any = {};
  constructor(private movieDataService: MovieDataService) {}

  ngOnInit(): void {
    this.movieDataService.getData().subscribe((data) => {
      this.movieData = data;
      // Display JSON data in the console
      console.warn(data);
    })
  }
}

Here is the HTML code for the homepage:


<div class="wrapper-grid">
    <div *ngFor="let result of movieData.results;" class="container">
      <img routerLink="/movieInfo" src='https://image.tmdb.org/t/p/w780{{result.poster_path}}'   alt='thumbnail' class="thumbnail-img">
      <info-page [movieId]="result.id"></info-page>
      <p class="home-text">{{result.title}}</p>
      <p class="home-date">{{result.release_date}}</p>
    </div>
</div>

The Single movie page is responsible for rendering the selected movie's data:


import { Component, Input, Output, EventEmitter } from '@angular/core';
import { single } from 'rxjs';
import { DataService } from '../services/data.service';

@Component({
  selector: 'info-page',
  templateUrl: './info-page.component.html',
  styleUrls: ['./info-page.component.css']
})
export class InfoPageComponent {

  @Input()
  movieId: number;

  singleMovieData: any = {} ;

  constructor(private DataService: DataService) {}

  getMovie() {
    this.DataService.getMovie(this.movieId).subscribe((data: any) => {
      this.singleMovieData = data;
    })
  }

  ngOnInit(): void {
    this.getMovie()
  }

}

Service for the Single Movie page:


import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  movieId: number;

  public getMovie(movieId: number) {
    return this.http.get(`https://api.themoviedb.org/3/movie/${movieId}?  api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US`);
  }

}

At present, each function appears to be functioning properly - the correct information is retrieved when logging the movieId and singleMovieData. However, I am encountering a 404 error when executing the GET request in the service on the Single Movie Page, with the message indicating that the parameter for movieId is undefined. If anyone can assist me in identifying what may be causing this issue, I would greatly appreciate it.

Answer №1

The issue lies in the incorrect setting of the movieId property within the DataService. This results in an undefined movie ID parameter in the API URL, leading to a 404 error when making the GET request.

To fix this, it is recommended to eliminate the movieId property from the DataService class and instead pass the movieId parameter directly to the get() method within the getMovie() function. By doing so, the movieId parameter will be properly included in the API URL for the GET request, resolving the 404 error:

import { Injectable } from '@angular/core';
import { HttpClient } from '@common/http';
@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private http: HttpClient) {}
  public getMovie(movieId: number) {
    return this.http.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US`);
  }
}

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

An effective method to utilize .map and .reduce for object manipulation resulting in a newly modified map

Here's an example of what the object looks like: informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0 ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Adding a local image to Firebase Storage in Angular5 / Ionic3

Uploading images is a breeze using the following method (select input file): import { AngularFireStorage } from 'angularfire2/storage'; @Component({ selector: 'app-root', template: '<div>' + '<input c ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Inputting data types as arguments into a personalized hook

I am currently developing a Next.js application and have created a custom hook called useAxios. I am looking to implement a type assertion similar to what can be done with useState. For example: const [foo, setFoo] = useState<string>(''); ...

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

There seems to be a malfunction with the routing feature in the src/index.html file

My routing setup is not functioning as expected in src/index.html angular. What I have is a header with some links for navigation: <header> <div class="logo"> <div class="logo-img-div"> <img src="../../ass ...

What is the best way to initiate multiple processes in Node.js and ensure they finish before proceeding?

When working with Node.js and TypeScript, my goal is to initiate multiple processes using the spawn function. Afterwards, I aim to ensure all of these processes are completed before proceeding to execute any additional commands. ...

The Ion-item-option button requires two clicks to activate

Within my ion-list, I have sliding items that are dynamically created using a for loop. Interestingly, when clicking on an item to navigate to another page, everything works fine. However, upon sliding an item, a button is revealed but it requires two clic ...

Issue arises when compiling React Redux due to a union type that includes undefined

I am currently in the process of learning how to integrate Redux with React using Typescript. I encountered a compilation error that relates to the type of my store's state, specifically as {posts: PostType[]}. The error message states: Type '{ p ...

Comparing dates in Angular 6 can be done by using a simple

Just starting with angular 6, I have a task of comparing two date inputs and finding the greatest one. input 1 : 2018-12-29T00:00:00 input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time) The input 1 is retrieved from MSSQL database and the in ...

Incorporating Angular 6 and NodeJS 8.4 with the MEAN stack, I aim to display the current status of all identifiers stored in MongoDB directly onto the browser

After successfully storing the list of objects in MongoDB, I have implemented a functionality to display all items on the browser. When the inventory button is clicked, the routerlink is used to fetch the availability and list them accordingly. Now, I am ...

The FirebaseX Ionic native plugin received 2 arguments instead of the expected 3-4

Trying to implement Firebase Phone Auth with the FirebaseX plugin, I encountered an issue. Here is the code snippet I used: async getVerificationCode(): void { const res:any = await this.firebaseX.verifyPhoneNumber('+16505553434', 60); ...

Undefined error encountered in the Google Places library

I'm new to working with the Ionic framework and was experimenting with implementing an autocomplete search feature using the Google Maps API. After going through several resources, I included the following code: <script type="text/javascript" src ...

Tips for incorporating flow and TypeScript typings into an NPM module

Are there any resources available for adding both flow and typescript typings to an NPM module at the same time? I've been struggling to find a comprehensive guide on this topic, and it seems to be a common issue faced by open source library maintain ...

Transitioning from Angular Http to HttpClient: Overcoming Conversion Challenges

Currently, I am in the process of converting my old Angular app from Http to HttpClient. While working on the service.ts section, I encountered an error that I am struggling to resolve: ERROR Error: Cannot find a differ supporting object '[object Ob ...

NextAuth is failing to create a session token for the Credential provider

Currently, I am in the process of developing an application using the t3 stack and am facing a challenge with implementing the credential provider from nextauth. Whenever I attempt to log a user in, I encounter an error in the console displaying the messag ...

Tips for obtaining the OneSignal playerID

When launching the app, I need to store the playerID once the user accepts notifications. This functionality is located within the initializeApp function in the app.component.ts file. While I am able to retrieve the playerID (verified through console.log) ...

Angular ngx-translate not displaying image

My Angular application is utilizing ngx-translate to support multiple languages. I am trying to dynamically change an image based on the language selected by the user. However, I am facing difficulty in updating the image when a language is clicked. The ap ...