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

What is the simplest way to incorporate Vue with Typescript, without the need for a complex build setup?

I've been spending the last couple of days experimenting with my basic ASP.NET Core website set up for Typescript 2.9, but unfortunately, I haven't made much progress. My main goal is to keep the front-end simple, with just single Vue apps on eac ...

Angular 2 setting a class property to the output

There seems to be an issue with logging to the console in my getProfile() method. When I assign this.user to user, it does not return my json object as expected. If I write the following code: getProfile() { this.userService.getPortInfo() .th ...

How can TypeScript be used to enable CSV or PDF export in a material-react-table?

Is it possible to incorporate the ability to export data to CSV or PDF in a material-react-table? While I am familiar with how to do this with a Material UI table, I have not been able to find the same functionality for the material-react-table. Thank you ...

Encountering an error in resolving a dependency while attempting to run 'npm

I'm working with Angular version 13 at the moment. Encountered some errors when trying to execute the npm install command. Any suggestions on how to resolve these issues? > npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE could not solve npm ...

What could be causing ConnectedProps to incorrectly infer the type?

My redux state is rooted and defined as: interface RootState { users: User[] } When working with components, I want to utilize ConnectedProps to generate the props type automatically from my state mapping and dispatch mapping: const mapState = (state: ...

Why isn't the class applying the color to the Angular span element?

My Angular application generates text that needs to be dynamically colorized. To achieve this, I inject a span element with a specific class into the text output like so: Some text <span class="failResult">that's emphasized</span> and oth ...

sending information to ng-content from mother in Angular

In the container-page.component.ts, I have set up the following structure using the ngrx approach. <parent-comp><child-comp [someInput]="someValue"></child-comp></parent-comp> Within the template of parent-comp, there is: <div ...

Expanding the header in Ionic 3 with a simple click event

I have successfully implemented an Expandable Header in Ionic 3 following a tutorial from Joshmorony. The header expands perfectly on scroll, as you can see in this GIF: However, I am facing an issue where I want to expand the header on click instead of o ...

What are some strategies for validating form fields in the Back-End and displaying them in Angular7?

My plan is to develop the backend of my app using Spring Boot and the frontend using Angular. I want to ensure the security of the form field information by validating it on the backend side. To get started, I created a model called Visitor.java with the f ...

Route user based on login status using router

I want to set up automatic routing to a login page for users who are not logged in. app.module.ts import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from &ap ...

Exploring the functionality of the Angular 7 date pipe in a more dynamic approach by incorporating it within a template literal using backticks, specifically

I have a value called changes.lastUpdatedTime.currentValue which is set to 1540460704884. I am looking to format this value using a pipe for date formatting. For example, I want to achieve something like this: {{lastUpdatedTime | date:'short'}} ...

I find myself hindered by TypeScript when trying to specify the accurate constraints for getUserMedia

I'm having difficulty getting a screen to stream within my Angular 5 Electron application. I am utilizing the desktopCapturer feature provided by Electron. Below is an excerpt of my code: loadCurrentScreensource() { desktopCapturer.getSources({ ...

Dealing with Angular State Management Across Components (Direct Dependency): encountering a NullInjectorError - R3InjectorError

I have encountered a NullInjectorError in my Angular application and I am seeking assistance in resolving it. To provide context, my application consists of three main components: ProductRegistrationAndListingScreen, ProductList, and ProductRegistration. ...

Ways to expand the DOM Node type to include additional attributes

I've been diving into typescript and transitioning my current code to use it. In the code snippet below, my goal is: Retrieve selection Get anchorNode from selection -> which is of type 'Node' If anchorNode has attributes, retrieve attr ...

What is the best way to troubleshoot a quasar typescript file type error?

Currently, I am delving into Quasar using TypeScript and encountering a type error while working on file uploads. Here is the snippet of my code where the type error arises specifically in the parameter of the form.append() method. The error message read ...

What is the significance of `new?()` in TypeScript?

Here is a snippet of code I'm working with in the TypeScript playground: interface IFoo { new?(): string; } class Foo implements IFoo { new() { return 'sss'; } } I noticed that I have to include "?" in the interface met ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

"Unexpected compatibility issues arise when using TypeScript with React, causing errors in props functionality

Just the other day, my TypeScript+React project was running smoothly. But now, without making any changes to the configurations, everything seems to be broken. Even rolling back to previous versions using Git or reinstalling packages with NPM does not solv ...

Looking to display the ng-option in two lines within Angular 6?

How can I display data in a select dropdown with two lines for each option? I am currently using ng-select. <ng-select [(ngModel)]="selectedData" placeholder="Select Data"> <div *ngFor="let data of Data"> <ng-option [value]="da ...