The type 'HttpEvent<MovieResponse>' does not contain a property named 'results'. This is causing a TypeScript Error

I'm currently integrating the TMDB trending movies endpoint into my Angular 18 application and storing the data in a variable.

Here is a snippet of the code:

private trendingMovies$ = this.http.get<MovieResponse>(${this.apiUrl}trending/movie/day, this.options).pipe(
    map((data) => {
      data.results.map((movie: Movie) => ({
        ...movie,
      }) as Movie)
    }),
    shareReplay(1),
  );

However, I'm encountering a TypeScript error regarding the 'results' property on the data object within the map operator:

Property 'results' does not exist on type 'HttpEvent<MovieResponse>'.
  Property 'results' does not exist on type 'HttpSentEvent'.ts(2339)

I have defined an interface for the response and for the individual movie object within the array of results:

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

export interface Movie {
  adult: boolean;
  backdrop_path: string;
  genre_id: Number[];
  id: Number;
  media_type: string;
  original_language: string;
  original_title: string;
  overview: string;
  popularity: Number;
  poster_path: string;
  release_date: string;
  title: string;
  video: boolean;
  vote_average: Number;
  vote_count: Number;
}

I have checked the response using the tap operator and confirmed that it does have a 'results' property, so I'm unsure why I'm getting this TypeScript error. I have tried adding a type to the line in question, but the error persists:

map((data: MovieResponse) => {

Any assistance on resolving this issue would be greatly appreciated.

Answer №1

Consider including observeOn: 'body' in your code. This might be the cause of the problem. When the observe type is set to response, the type is changed to HttpEvent<MovieResponse>, leading to the issue.

Original Code Snippet:

private trendingMovies$ = this.http
    .get<MovieResponse>(`${this.apiUrl}trending/movie/day`, { observe: 'response' })

Updated Code Snippet:

private trendingMovies$ = this.http
    .get<MovieResponse>(`${this.apiUrl}trending/movie/day`, { observe: 'body' })

Check out the Stackblitz Demo

Answer №2

It is recommended to specify the type of variable data when using map:

map((data:MovieResponse ) => ...
//or
map((data:any) => ...

However, ensure that your map function includes logic to transform the response data:

   map((data) => {
      data.results.map((movie: Movie) => ({
        ...movie,
      }) as Movie)
      return data //<--else you transform in null the response
    })

Keep in mind that while TypeScript helps prevent errors, it does not guarantee the response type will always match what you specify after transpiling to JavaScript.

Answer №3

Appreciate the assistance, the replies really helped me resolve the issue with my code. It seems that the problem stemmed from the options object attached to the request.

private options = {
    method: 'get',
    headers: {
      accept: 'application/json',
      Authorization: '<auth token here'
    }
  }

After realizing that the method property was unnecessary, I removed it and the error disappeared.

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

Can you explain the significance of this particular line in the source code of VSCode?

While browsing through the VS Code source code, I stumbled upon the following snippet: https://github.com/microsoft/vscode/blob/5da4d93f579f3fadbaf835d79dc47d54c0d6b6b4/src/vs/workbench/contrib/comments/browser/commentsEditorContribution.ts#L166 It appear ...

Using *ngFor to populate an array in an ion-list within Ionic 2

Hi there, I'm currently learning Ionic 2 and I recently created an array that I want to loop through in an ion-list. This is my produk.ts import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angul ...

The Angular router-outlet is refusing to display any content

I am new to Angular and currently learning through a lecture with hands-on practice. I have written the code below as instructed by my teacher, but it's not displaying anything on the screen. Can someone please assist me? app.module.ts : @NgModule({ ...

JS : Removing duplicate elements from an array and replacing them with updated values

I have an array that looks like this: let arr = ['11','44','66','88','77','00','66','11','66'] Within this array, there are duplicate elements: '11' at po ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

Tips for managing errors when utilizing pipe and mergemap in Angular

In the code snippet provided, two APIs are being called. If there is an error in the first API call, I want to prevent the second API call from being made. Can you suggest a way to handle errors in this scenario? this.userService.signUp(this.signUpForm.v ...

How do I steer clear of this nested subscription when working with Angular Material's dialog box?

This is my current setup: this.entitiesManagementService.searchAddressEventEmitter$.pipe(switchMap((_) => { const formValue = this.addressAttributesSearchForm.getRawValue(); return forkJoin([ this.entitiesManagementService.getAddressClassificati ...

Executing a cloud function in Firebase from an Angular-Ionic application by making an HTTP request

I am a newcomer to GCP and app development, so please bear with me if this question seems mundane. Currently, I have an angular-ionic app that is connected to Firebase allowing me to interact with the Firestore database. Now, my challenge is to invoke a ht ...

Module '@tanstack/react-table' cannot be located even though it has been successfully installed

Currently, I am tackling a TypeScript React project and encountering an issue while attempting to import ColumnDef from @tanstack/react-table in my columns.tsx file. import { ColumnDef } from "@tanstack/react-table"; export type Payment = { id ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

Typescript - Issue with accessing Express Response object

Having trouble using the methods of the Response object in my TypeScript method. When I try to log it, all I get is an empty object. It seems like the import is not providing the response as expected. import { Response } from 'express'; async sen ...

Exploring Angular 5: Injecting a Service in Unconventional Places

I am attempting to utilize a service outside of a component. My main objective is to use my service within a function wrapped in a data object that I would then pass to my router for use by my Breadcrumb later on. Here is an example of what I envision: ...

Before the service call finishes, Akita queries this.selectAll and returns an empty list

Here is the code snippet from my file named widgetquery.ts: @Injectable({ providedIn: 'root' }) export class WidgetQuery extends QueryEntity<WidgetState, WidgetTO> { public Widget$: Observable<WidgetTO> = this.selectActive().filter( ...

A guide to fetching responses using the axios API in React Native using the "GET" method

Below is the code snippet that I am working with: axios({ method: "GET", url: "http://112.196.108.244:9002/api/survey/question/get-question/not-answered/?surveyId=", headers: { "content-type": "application/json& ...

The most effective method for transferring a JavaScript object between a TypeScript frontend and a Node.js backend

I need some advice on how to effectively share a JavaScript object between my Angular2 with Typescript frontend and NodeJS backend in an application I'm working on. Currently, I am using a .d.ts file for the frontend and adding a module.exports in the ...

Can TypeScript restrict a callback parameter based on the type of another parameter using generics?

I am currently developing an event manager system. The main objective is to allow users to subscribe to events by providing an event type and a callback function. In my implementation, events are represented as classes, where AwesomeEventType in the exampl ...

Sharing information with child components in Angular

I am currently working with Angular and I have two child components that I need to pass data to. In the home template, my code looks like this: <div class="myCard"> <mat-card style="width: 500px;"> <mat-card-tit ...

How can one determine the source of change detection activation in Angular 2?

I just launched a new component and it appears to be causing change detection to occur multiple times per second: // debugging code ngDoCheck() { console.log('DO_CHECK', new Date().toLocaleTimeString()); } Results: https://i.sstatic. ...

Passing data to an Angular 8 router can be done easily with this simple guide

In a situation where I have a list of products on a page and wish to transmit a product ID to a /product/:id router without resorting to parsing it from the URL directly, what alternatives exist? Is there a way to implement functionality akin to an Input ...

Unable to bring in the directive from the Angular library

I've created this custom Directive within my library: @Directive({ selector: '[layoutHeaderTitle]', standalone: true }) export class HeaderDirective { constructor( readonly tpl: TemplateRef<any>, private re ...