How can I resolve the Angular 16 app error related to the missing 'results' property?

Lately, I've been immersed in developing a Single Page Application (SPA) using Angular 16, TypeScript, and The Movie Database (TMDB).

Within

app\services\movie-service.service.ts
, my code snippet looks like this:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { MovieResponse, Movie } from '../models/Movie';

@Injectable({
  providedIn: 'root'
})

export class MovieService {

  constructor(private http: HttpClient) { }

  public getMovies(): Observable<MovieResponse[]> {
    return this.http.get<MovieResponse[]>(`${environment.apiUrl}/movie/now_playing?api_key=${environment.apiKey}`);
  }
}

The structure of the model app\models\Movie.ts is defined as follows:

export interface Movie {
    id?: number;
    adult?: boolean;
    backdrop_path?: string;
    poster_path?: string;
    title?: string;
    tagline?: string;
    overview?: string;
    genre_ids?: any;
    original_title?: string;
    release_date?: string;
    runtime?: number;
    vote_average?: string;
}

export interface MovieResponse {
    results?: Movie[];
    total_pages?: number;
    total_results?: number;
    page?: number;
}

When attempting to display movies on the HomePageComponent, here is the code snippet being used:

import { Component } from '@angular/core';
import { MovieResponse, Movie } from '../../models/Movie';
import { MovieService } from '../../services/movie-service.service';


@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.scss']
})
export class HomePageComponent {

  public movieResponse!: MovieResponse[];

  public movies: Movie[] = [];

  constructor(private movieService: MovieService) { }

  public getMovies() {
    this.movieService.getMovies().subscribe((response) => {
      this.movieResponse = response;

      console.log(this.movieResponse);

      this.movies = this.movieResponse.results;
    })
  }

  ngOnInit() {
    this.getMovies();
  }
}

While console.log(this.movieResponse) correctly displays the response data with results, total_pages, etc;

The dilemma

The line

this.movies = this.movieResponse.results
triggers the error message:

TS2339: Property 'results' does not exist on type 'MovieResponse[]'.

Inquiries

  1. What am I missing or doing incorrectly?
  2. How can I go about resolving this issue effectively?

Answer №1

Within the movieResponse, there are numerous objects (referred to as movie responses), each containing its own results property.

Given that the request payload is not shared, we only need to access the results of the initial element.

Instead of accessing the entire array, you can simply access a single element within it!

  public getMovies() {
    this.movieService.getMovies().subscribe((response) => {
      this.movieResponse = response;

      console.log(this.movieResponse);

      this.movies = this.movieResponse[0].results; // <- modification made here!
    })
  }

If the API returns just one movie response, then make the following code adjustment by replacing MovieResponse[] with MovieResponse

  public getMovies(): Observable<MovieResponse> {
    return this.http.get<MovieResponse>(`${environment.apiUrl}/movie/now_playing?api_key=${environment.apiKey}`);
  }

ts

export class HomePageComponent {

  public movieResponse!: MovieResponse;

  public movies: Movie[] = [];

  constructor(private movieService: MovieService) { }

  public getMovies() {
    this.movieService.getMovies().subscribe((response) => {
      this.movieResponse = response;

      console.log(this.movieResponse);

      this.movies = this.movieResponse.results;
    })
  }

  ngOnInit() {
    this.getMovies();
  }
}

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

How to dynamically assign a type based on a single choice from multiple options (props)

I have a props object that includes: { option1, option2, option3, option4, general, otherProps } The requirement is to allow only one option to be used at a time. Here are the types defined: interface MyTypes { option1: boolean option2: boolean option3 ...

What sets apart isSuccess from onSuccess in react-query?

When the useMutaion is successful, I would like to implement some logic. However, I am not sure whether to use the boolean 'isSuccess' or the callback function 'onSuccess'. Can you advise on the best approach? const { mutate: creat ...

An easy way to insert a horizontal line between your text

Currently, I have two text responses from my backend and I'm considering how to format them as shown in the design below. Is it possible to automatically add a horizontal line to separate the texts if there are two or more broadcasts instead of displa ...

Whenever the download bar emerges at the bottom, the slideshow content on the page suddenly shifts upwards

Each time the download bar shows up at the bottom, the slideshow content on the Homepage suddenly moves up. It returns to its original position after I close the download bar.https://photos.app.goo.gl/F482eMfkXyfEZkdA9. My assumption is that this issue is ...

Is it possible to use jQuery/JS to automatically format currency input as it is typed, adding a 1000 separator and ensuring

I'm working on a text input field that needs to format the value as it is being typed, with restrictions of 2 decimal places and 1000 separators. This field should only allow for digits to be entered. Specifically, this input is meant for users to ent ...

How to save data to a JSON file using the filesystem module in Node.js

After coming across this helpful guide at , I was intrigued by the creation of a point system in discord.js. The use of let points = JSON.parse(fs.readFileSync("./points.json", "utf8")); to read the file piqued my interest, leading me to explore how to bui ...

"Converting circular structure into JSON" - Inserting BigQuery Data using Cloud Function in Node.js

I am currently facing an issue while attempting to load an array of JSON objects into a BigQuery Table from a Cloud Function built in NodeJS. Despite not having any circular references, I encountered the error message "Converting circular structure to JSON ...

What is the process for incorporating a script function into a React application?

Recently, I've been attempting to integrate the external application Chameleon into my React application. To achieve this, I need to incorporate the javascript function within my application. I prefer it to be invoked only in specific scenarios, so I ...

The webkitTransitionEnd event fires prior to a repaint or reflow occurring

My goal is to create a progressBar that changes its width when an ajax request is made. I want the ajax callback to only execute after the animation of the progressBar is complete. Here is the code I am using: CSS: #progressBar{ position: fixed; ...

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Methods for transferring the true/false state of a semantic checkbox to e.target

In order to pass the values of state.TNC and state.promos into the emailjs.sendForm, the submitted email should display 'true' if the box is checked, and 'false' if not. I am struggling to find a solution that involves semantics and em ...

AngularJS uses double curly braces, also known as Mustache notation, to display

I'm currently working on a project where I need to display an unordered list populated from a JSON endpoint. Although I am able to fetch the dictionary correctly from the endpoint, I seem to be facing issues with mustache notation as it's renderi ...

Guide on saving a Facebook image to a web server directory with Node.js and Express

Looking for some help here - I'm trying to download and save images from a user's Facebook album onto my server folder. My server is running on node.js and express, but when I tried using http.get it didn't work. Any advice or solutions wou ...

What is the best way to send information from App.js to components?

In my project, I am working with App.js and a functional component called "uploadlist". The goal is to pass a 'custid' value from App.js to the uploadlist component. Here's what I have attempted: app.js: export default class App extends Com ...

Node.js Dynamic JSON References

In my JSON file "jFile", the structure is as follows: { "Entry1": null, "Entry2": "SomeValue" } I have some node.js code that successfully updates the file content like this: jFile.Entry1 = "SomeText"; fs.writeFileSync( "jFile.json", JSON.stringif ...

The error "TypeError: b.toLowerCase is not a function in the bootstrap typeahead plugin" indicates that

Currently, I am working on implementing autocomplete search using the typeahead plugin version 3.1.1. My implementation involves PHP, MySQL, AJAX, and JavaScript/jQuery. While everything works perfectly with mysqli in terms of displaying suggestions when t ...

Support for ViewEncapsulation.ShadowDom now available in Edge, Internet Explorer, and legacy browsers

I am working with Angular 7 and material design. Some of my components utilize ShadowDOM ViewEncapsulation, leading to errors in older versions of IE, Edge, Chrome, and Firefox. Below is the error message I am encountering: Object doesn't support pr ...

Issues encountered when trying to implement helperText in mui date picker

Can someone assist with this issue? The helper text is not displaying as expected in the following code snippet: <div className={classes.container}> <LocalizationProvider dateAdapter={AdapterDateFns}> <Des ...

Achieving click detection on a link within an iframe in Angular 2

Is there a way to detect a click on a link within an iframe? <iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"></iframe> Inside my iframe component, I have a simple code that listens to changes in observable var ...

Next.js encountered an error with Mapbox-gl-geocoder: TypeError - EventEmitter cannot be used as a constructor

In my ongoing Next.JS version 13 project, I have been successfully using Mapbox-GL and mapbox-gl-geocoder. However, recently I encountered an error when accessing the map that reads: EventEmitter is not a constructor at new MapboxGeocoder (webpack-interna ...