Passing information from the main component to a service through API connections

Currently, I am in the process of developing a website dedicated to showcasing the top 20 highest-rated Sci-fi movies. The main component on the homepage leverages a GET request via a service to fetch an array of objects containing the movie data. This movie data is then displayed using `ngFor*` in the HTML template.

Each movie thumbnail on the homepage has a click handler that navigates to a separate page for more detailed information about the selected movie, including its description and ratings. For this secondary page, a service is utilized to make another GET request, with the query parameter being the ID of the selected movie.

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;
          // Output JSON to console
          console.warn(data);
        })
      }
    }`

Service used for the homepage:

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

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

       constructor(private http: HttpClient) { }
  
       getData() {
         return this.http.get('https://api.themoviedb.org/3/discover/movie?api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US&with_genres=878');
       }
     }`

The Single Movie page which will display the chosen movie's data:

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

    @Component({
      selector: 'info-page',
      templateUrl: './info-page.component.html',
      styleUrls: ['./info-page.component.css']
    })
    export class InfoPageComponent {
  
      singleMovieData: any = {} ;
  
      constructor(private DataService: DataService) {}


      ngOnInit(): void {
        this.DataService.getMovie().subscribe((data) => {
          this.singleMovieData = data;
          console.warn(data);
        })
       }
    }`

Service used 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 = 505642;
       getMovie() {
         return this.http.get(`https://api.themoviedb.org/3/movie/${this.movieId}?api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US`)
  }
}

As of now, I have hardcoded a movieId into the query, which is functional. Since I am still relatively new to Angular, I am exploring ways to dynamically capture the selected movie's id upon clicking, pass it to the service, and execute a GET request with that ID as one of the query parameters.

Answer №1

Make sure to include the movieId parameter in each instance of your InfoPageComponent, which is a child component.

home-card.component.html

<div *ngFor="let movie of movies;">
  <info-page [movieId]="movie.movieId"></info-page>
</div>

info-page.component.ts

export class InfoPageComponent {
  @input()
  movieId: number;

  ....
  getMovie() {
    this.dataService.getMovie(this.movieId).subscribe(...);
  }
}

Answer №2

Together with paranaaan's response,

info-page.service.ts

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

Answer №3

  • Establish the route

{ path: 'movieInfo/:id', component: InfoPageComponent }

  • Proceed to the designated route

<a [routerLink]="['/movieInfo', movie.id]">{{movie.name}}

  • Retrieve the parameter from the route in InfoPageComponent

this.id=this._Activatedroute.snapshot.paramMap.get("id");

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

Unlocking the TypeScript UMD global type definition: A step-by-step guide

I have incorporated three@^0.103.0 into my project, along with its own type definitions. Within my project's src/global.d.ts, I have the following: import * as _THREE from 'three' declare global { const THREE: typeof _THREE } Additio ...

Utilizing CSS in Angular applications

I am currently working on an Angular 2 application and I am fairly new to Angular. I am facing an issue where my CSS does not seem to be applying properly. There are three key files involved: landing.component.html landing.component.scss landing.compone ...

Transforming time into luxon time frames and hours

Is there a way to convert this block of code from moment.js to luxon? Here is the code snippet for reference: The following code is written using moment.js, but I would like to achieve the same functionality using luxon. timezone: null, getIn: moment() ...

I am unable to generate an Angular file

PS D:\AngularCalismalar> ng new intro Node.js version v17.1.0 was detected. It is recommended not to use odd numbered Node.js versions for production as they will not enter LTS status. For more information, visit https://nodejs.org/en/about/relea ...

Update to Angular 6 and experience issues with the Test functionality

At first, I started a project with Angular 5. As I progressed, I made the decision to upgrade to Angular 6. After the upgrade to Angular 6, I made some necessary adjustments to the code. However, when running the Test, I encountered an issue. https://i. ...

Dealing with the Angular 7 ExpressionChangedAfterItHasBeenCheckedError in combination with NgsScrollReveal

Utilizing ngScrollReveal triggers a re-render with every scroll event. I am invoking a function through the HTML in this manner: <component [alternate]="toggleAlternate()"> The code for toggleAlternate() is as follows: toggleAlternate() { this.a ...

Exploring the implementation of TypeScript Generics in react-hook-form interfaces

This is the code I have: export interface PatientFormInputs { patientId: string; firstName: string; lastName: string; email: string; day: string; month: string; year: string; } In a React component: const { control, register, h ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Display excerpts of code within an Angular application within the HTML segment

I'm currently developing a tutorial page using Angular where I intend to display code snippets in various programming languages such as 'Java', 'TypeScript', 'C#', and 'Html'. Although there is a snippet called ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

How to Disable Back Button During Angular 2 REST API Requests?

Within my Angular 2 application, a REST API call is made to process a functional flow and receive a response from the server. During this process, I want to prevent users from navigating using the browser's Back button. To achieve this, I have implem ...

Encountering error code TS1003 while trying to access object properties using bracket notation in Typescript

How can object property be referenced using bracket notation in TypeScript? In traditional JavaScript, it can be done like this: getValue(object, key) { return object[key]; } By calling getValue({someKey: 1}, "someKey"), the function will return 1. H ...

Issue arises when fastify/websocket is being used and an argument of type '{ websocket: boolean; }' is not compatible or able to be assigned to a parameter

I am facing an issue with my new project that involves fastify and Typescript. The error I am encountering is as follows: Argument of type '{ websocket: boolean; }' is not assignable to parameter of type 'RouteShorthandOptions ...ts(2345) B ...

I'm looking for the best place to place code for initialization before initializing a custom module in Angular 14

Using ngrx/data 14 and Angular 14, I have constructed a unique custom module that I include in my app.module.ts file as follows: @NgModule({ declarations: [ AppComponent ], imports: [ ... AppRoutingModule, MyCustomModule, ... ] ...

Using RxJS with Angular to intercept the valueChanges of a FormControl prior to subscribing

I decided to create a new observable using the values emitted by the FormControls.valueChanges observable. This creation of the observable takes place within the ngOnInit method in the following manner: ngOnInit(): void { this.myObservable$ = combine ...

What is the process for enabling keyboard selections in a Material-UI Select component?

Is there a way to make the MUI Select component keyboard accessible by tabbing into it and using the first letter of the option to auto-select without opening the list? I am looking for a feature where pressing the initial letter selects the first item tha ...

Having trouble with Angular 2 and ng2-file-upload when trying to load it using SystemJS

Currently, I am utilizing systemJS for package management in my project. In order to configure systemJS, I have included the following lines in the configuration file: { map: { 'ng2-file-upload': 'node_modules/ng2-file-upload' }, p ...

What steps should be taken when encountering an error with fs while using ANTLR?

I have encountered an issue with antlr while using Angular in Visual Studio Code. I am familiar with including and writing a grammar in a project, but recently I ran into a problem when starting it: "ERROR in ./node_modules/antlr4/CharStreams.js Module no ...

retrieve user input from various angular 6 components

Currently, I am in the process of developing a small web-based game using Angular 6. Within this project, I have two key components - play.component and setup.component. The main concept is to allow users to customize elements such as difficulty within the ...

I encountered an issue when attempting to display a validation message on an Angular form

As I work on creating an Angular form and implementing validation, I encountered an issue when attempting to display a message when a field is left empty. My approach involved using ng-for in a span tag, but unfortunately, an error occurred. Here is the H ...