Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below:

  listTrendingMovies() {
    this.listMediaService.listTrendingMovies().subscribe((res) => {
      this.trendingMovies = res['results'];
    });
  }

The object "results" contains an array with unique IDs for each movie, which can be found in their documentation.

To fetch and subscribe to genre data in genresList:

  listGenres(){
    this.listMediaService.listMovieGenres().subscribe((res) =>{
      this.genresList = res['genres']
    })
  }

The "genres" object also includes an array with IDs corresponding to each genre, as noted in the documentation.

I have implemented a function that retrieves the name of each genre based on its ID:

  findGenre(genreId){
    this.genresList.forEach((obj) =>{
      if (genreId == obj.id){
        this.genreName = obj.name
        console.log(obj.name)
      }
    })
  }

Although I have made progress up to this point, I am facing an issue. While I am able to access specific genres using their IDs and both objects contain movie and genre information, I am struggling to link each movie displayed in my component.html (using ngFor) with its corresponding genre from the genres object.

Your assistance would be greatly appreciated!

Answer №1

It seems like you're just starting out with programming, not only Angular. I will assist you by providing a simplified version of what you want to achieve - focusing on finding and filtering data without the UI part.

Let's say the task is to create a drop-down menu of genres for users to choose from, which then displays a list of movies that match the selected genre.

Assuming you already have the user interface set up for selecting the genre and displaying the films:

  1. In JavaScript/TypeScript, there are easier methods to find items in an array instead of manually looping through it.
public findGenre(genreId: number): Genre | undefined {
    return this.genres.find(x => x.id === genreId);
}

The .find function will either return the first matching value or undefined if no match is found.

  1. Now, let's address your main question - how to retrieve films based on a specific genre.

You actually don't need to fetch the genre before finding the films. If the API documentation states that film objects include genre IDs, you can directly filter the films using the genre ID.

Assuming you have an array called 'showFilms' which lists the films displayed in your template:

public setFilmsForGenreId(genreId: number): void {
    this.showFilms = this.films.filter(x => x.genre_ids.includes(genreId));
}

The .filter method will return multiple results (or an empty list) that meet the criteria. In this case, it checks whether the film's genre_ids includes the specified genre ID.

By calling the setFilmsForGenreId method with the chosen genre ID after selection, the showFilms array will be updated with films of that genre. You can then use

*ngFor="let film of showFilms"
in your template to display them.

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

Received 2 arguments instead of the expected 1 in the custom validator causing an error (ts 2554)

After implementing the following validator, I encountered an error message. The error states: "Expected 1 argument, but got 2 (ts 2554)." Although many sources mention overloading as a common issue, there is no overload present in this case. export const ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

https://i.sstatic.net/fkIyh.png Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navig ...

Develop a professional Angular application for deployment

Help! I'm struggling to build my Angular application for production. After running the 'ng build --prod' command, I can't find all my components in the 'dist' folder. Do I need to change or configure something else? I see som ...

Imitate dependencies using Mocha and Typescript

In my typescript project, I am using mocha. Let's consider two modules: // http.ts export class Http { } // app.ts import Http from './http'; export class App { } I want to know how to mock the Http module while testing the App. The te ...

Implementing Immer in Typescript

Recently, I've been exploring the possibility of integrating Immer into my React project that already utilizes Typescript. Unfortunately, I haven't been able to discover a clear guide on how to effectively employ Immer in conjunction with Typescr ...

What is the proper way to incorporate ts-nameof in the gulp build process and encounter the error message: 'getCustomTransformers' is a compiler option that is not recognized

Utilizing ts-nameof in my TypeScript files, similar to this example in a .ts file: import 'ts-nameof'; export class MyTsNameOfTest { public testTsNameOf() { const nameString = nameof(console.log); } } My Gulp build task setup - followi ...

Steps to Turn Off Angular 2 Material Input Field

Please carefully review the Description below before proceeding: This is an HTML file containing code snippets: <div class="row col-md-2"> <mat-form-field appearance="outline" class="nameInput col-md-2"> <mat-label>One< ...

React error: The DatePickerProps generic type must have one type argument specified

Date Selection Component: import React from "react" import AdapterDateFns from '@mui/lab/AdapterDateFns'; import { LocalizationProvider } from '@mui/lab'; import { DatePicker, DatePickerProps } from '@mui/lab'; cons ...

Guidelines for displaying user profile information in the dashboard page through an Angular project, considering the different user types (user, super user, admin)

In my application, I have implemented the dashboard feature. There are three types of dashboards: the regular user dashboard, super user dashboard, and admin dashboard. The super user and admin dashboards include additional tables along with the data from ...

Angular Ionic: Unable to compare 'value'. Only arrays and iterable objects are permitted for differentiation

I attempted to display a list value and when I logged the value of the list, it appeared exactly how I wanted: unit value {id: 81, name: "3 BR Suite"} unit value {id: 82, name: "3 BR Grande"} unit value {id: 83, name: "Pool Villa&q ...

The React component using createPortal and having its state managed by its parent will remain static and not refresh upon state modifications

I am facing a problem that can be seen in this live example: https://stackblitz.com/edit/stackblitz-starters-qcvjsz?file=src%2FApp.tsx The issue arises when I pass a list of options to a radio button list, along with the state and setter to a child compon ...

Is there a way to retrieve the headers from the error callback when using the subscribe function?

When a user creates a post, I need to handle any error responses from the server that may occur. The post creation occurs in the UserService's createUser() method. Any errors are caught using the catch method and a new error is thrown. It is important ...

Error: Bitbucket pipeline does not have the necessary permissions to complete the operation

I encountered an error while building ng build on Bitbucket. My backend is Firebase. Can you help me figure out what I'm doing wrong? EPERM: operation not permitted, lchown '/opt/atlassian/pipelines/agent/build/node_modules/.cache/angular-buil ...

Ways to bring in a Typescript Vue project to a Javascript Vue

I am trying to incorporate this Calendar component into my Javascript Vue 3 project. To achieve this, I have created a new component in my project named ProCalendar.vue and copied the code from the example found in App.vue. Additionally, I have added the n ...

"Protractor encountered an issue when navigating to the most up-to-date Angular section in our

We are in the process of upgrading our application from AngularJS to the latest version of Angular. I am currently working on writing tests that transition from the AngularJS version of the app to the admin application, which is built using the latest ver ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

When using Framer Motion for page transitions alongside React Router DOM v6, the layout components, particularly the Sidebar, experience rerenders when changing pages

After implementing page transitions in my React app using Framer Motion and React-Router-DOM, I noticed that all layout components such as the sidebar and navbar were unexpectedly rerendering upon page change. Here's a snippet of my router and layout ...

Exploring the @HostBinding argument in Angular directives

Need help grasping the concept behind the @Hostbinding argument: Snippet of the code: import { Directive, HostBinding } from "@angular/core"; @Directive({ selector: '[appDropdown]' }) export class DropdownDirective { @HostBinding(&apos ...

The DatePicker in Angular2 and Typescript is unable to execute the property 'toggle' because it is undefined

I've encountered an issue with the calendar icon for angular2's datepicker. Whenever I try to click on it, I keep getting this error: TypeError: Cannot read property 'toggle' of undefined at Object.eval [as handleEvent] (Admiss ...

Troubleshooting form submission issues in Angular 4

I am encountering a few issues with my search form. It is supposed to function as a search tool with one input field and one button. However, something seems amiss. I am utilizing an API that returns values based on the string inputted. When an empty value ...