Resolved error: Angular 'title' identifier is undefined. The 'Movie[]' array does not have this member

Attempting to fetch data from the backend using Angular services.
After reading the Angular docs, it was mentioned that interfaces should be used when sending requests somewhere
It should look something like this:

return this.http.get<Movie[]>(this.movieAPI)

Successfully subscribed to the service, but encountered an error from the compiler :

ERROR in app/movie/movie-detail/movie-detail.component.html:4:12 - error TS2339: Property 'title' does not exist on type 'Movie[]'.

Seems like the interface doesn't recognize the properties
These are my files

movie.ts (interface)

export interface Movie {
  id: number
  title: string
}

movie.service.ts

import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs'
import { Movie } from './movie'

@Injectable({
  providedIn: 'root'
})
export class MovieService {
  movieAPI = '../../assets/movie.json' // mock data
  api = '' // api removed

  constructor(
    private http: HttpClient
  ) {}

  getMovies(): Observable<Movie[]> {
    return this.http.get<Movie[]>(this.movieAPI)
  }

  searchMovie(params?: string): Observable<Movie[]> {
    return this.http.get<Movie[]>(`${this.api}/${params}`)
  }
}

movie.component.ts

import { Component, OnInit } from '@angular/core'
import { ActivatedRoute } from '@angular/router'
import { MovieService } from '../../movie/movie.service'
import { Movie } from '../../movie/movie'

@Component({
  selector: 'app-movie-detail',
  templateUrl: './movie-detail.component.html',
  styleUrls: ['./movie-detail.component.scss']
})
export class MovieDetailComponent implements OnInit {
  params: string
  movie: Movie[]

  constructor(
    private activatedRoute: ActivatedRoute,
    private movieSerivce: MovieService
  ) {
    this.getParams()
  }

  ngOnInit(): void {
    this.getDetail()
  }

  getDetail(): void {
    this.movieSerivce.searchMovie(this.params)
      .subscribe(
        (data:Movie[]) => this.movie = data
      )
  }

  getParams(): void {
    this.params = this.activatedRoute.snapshot.paramMap.get('id')
  }

}

movie.component.html

<h1>
  {{ movie?.title }}
</h1>
{{ movie | json }}

[Updated]
in movie.service.ts

...
searchMovie(params?: string): Observable<Movie> {
    return this.http.get<Movie>(`${this.api}/${params}`)
  }
...

in movie-detail.component.ts

...
getMovie(): void {
    const id = +this.activatedRoute.snapshot.paramMap.get('id')
    this.movieSerivce.searchMovie(`${id}`)
      .subscribe(
        (data:Movie) => this.movie = data
      )
}
...

Answer №1

The Movie interface includes the property title, while Movie[] does not.

In your code, this.movie is defined as type Movie[], indicating it is an array.

You can display the title of the first movie in the array like this:

<h1>
   {{ movie?[0].title }}
 </h1>

To make it more clear, consider changing movie: Movie[] to movies: Movie[].

You can iterate over the array using ngFor:

<h1 *ngFor="let movie of movies">
   {{ movie.title }}
 </h1>

If the getDetail method should only return a single movie, adjust the expected returned object like so:

movie: Movie;  

getDetail(): void {
    this.movieSerivce.searchMovie(this.params)
      .subscribe(
        (data:Movie) => this.movie = data
      )
  }
searchMovie(params?: string): Observable<Movie[]> {
    return this.http.get<Movie>(`${this.api}/${params}`)
}

Answer №2

When utilizing your service, the http request yields an array rather than a single object. This means that you cannot access inner properties directly from the array. To address this issue, consider using the following approach:

Implement ngFor to iterate through the array

<h1 *ngFor="let oneMovie of moviesArray">
  {{ oneMovie.title }}
</h1>

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

Why isn't Nodemon monitoring the directory in webpack-typescript-node.js?

Here are the contents of the package.json file for a TypeScript project using webpack and node.js: "scripts": { "build": "webpack", "dev:start": "nodemon --watch src --exec \"node -r dotenv/co ...

What is the appropriate Typescript return type to use for a $http request that only returns a successful response with no content?

I recently developed a Typescript service: class SettingsService implements ISettingsService { public info = {}; public backupInfo = {}; public userConfig = {}; public isLoaded = false; constructor( private $http: ng.IHttpSer ...

When implementing a sizable Angular material popover, ensure that the parent content is designed to allow scrolling

I have a custom popover feature in my current project, which includes checkboxes beneath the main content. Everything is functioning properly at the moment, but I've encountered an issue when the screen's resolution is reduced - the content at th ...

Confirm the Keycloak token by checking it against two separate URLs

In my system, I have a setup based on Docker compose with back-end and front-end components. The back-end is developed using Python Flask and runs in multiple docker containers, while the front-end is coded in TypeScript with Angular. Communication between ...

What is the best way to deploy static Angular builds for microservices on AWS S3 and ensure proper routing management?

Our Company's SAAS platform currently utilizes 7 to 10 Angular microservices, previously hosted on an EC2 engine with routing managed by Nginx. However, due to high costs associated with EC2, I have successfully migrated the website to a static websit ...

Analyzing feedback according to the ResponseHeaders

When sending a request to a REST API using http.get(), the response headers usually contain metadata related to page number, total results, and page count. Angular's HttpClient handles parsing and returning data from the response.body in an Observabl ...

Modify the state of a Babylon JS instance that was set up within an Angular 2 component

Hi there, I'm currently experimenting with injecting variables using Angular 2's Dependency Injection to alter the state of an object initialized within BabylonJS. I've tried using [(ngModel)]="Service.var" to access the variable and (ngMod ...

The React context hooks are failing to update all references

In my project, I am working on setting up a modal with a custom close callback. To achieve this, I used a useState hook to store the method and execute it within an already defined function called closeModal(). However, I encountered an issue when attempt ...

Dispatching an asynchronous function error in React with TypeScript and Redux - the parameter type is not assignable to AnyAction

Currently, I am in the process of developing a web application that utilizes Firebase as its database, along with Redux and TypeScript for state management. Within my code, I have a dispatch function nested inside a callback function like so: export const ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

I'm experiencing a strange issue where my React component renders twice in production mode, despite having strict mode turned off. Can anyone advise me on

Within my layout.tsx, I have a structure that encloses the page with a container div and introduces a separately defined TopBar component alongside. The functionality seems fine, but an issue arises where the component is created before the {children}, as ...

The functionality of Angularfire is not compatible with an Ionic capacitor app when running on iOS

I am encountering an issue with my Ionic, Capacitor, and AngularFire setup. While everything works smoothly on other platforms, I'm facing a problem specifically on iOS. The Firebase call does not return any data on iOS, and there are no visible error ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

Angular input for date is showing wrong value due to timezone problem

My database stores dates in UTC format: this.eventItem.date: "2023-06-21T00:00:00.000Z" The input form field value is showing '2023-06-20' (incorrect day number), which seems to be a timezone issue. I am located in a region with a +3 o ...

Angular 2 - Implementing click event functionality to add an item

I've searched for a solution to this before, but the best answer I could find was from 9 months ago: here and it doesn't work with the latest Angular version. Is there a way to add a new item (<li> or any other) to my HTML with a simple cl ...

File resolution issue with TypeScript

While I am aware that using TypeScript outFile is generally advised against, I currently have no choice but to utilize it until a more suitable solution like AMD can be implemented. It seems like there may be a "module splitting issue" in my project. In t ...

The data type 'unknown' cannot be assigned to the type 'any[]', 'Iterable<any>', or (Iterable<any> & any[])

I have been working on creating a custom search filter in my Angular project, and it was functioning properly. However, I encountered an error in my Visual Studio Code. In my previous project, everything was working fine until I updated my CLI, which resul ...

Adding animation to rows in ngx-datatable: A Guide

I am looking to stack the rows of my data table (ngx) one after the other in a vertical fashion. I want to incorporate [@datatableAnimation], but I'm unsure where to place it. When adding it to <ngx-datatable [@datatableAnimation]>, it only af ...

Passing dynamically loaded parameters to a function during dropdown value selection in Angular 2

Could you please review if I am passing the parameters correctly in the li tag's click function of the updateId method? The console errors only point to that line. This is my app.component.html code: <div class='form-group' style="width ...

Tips for postponing the listening observer experience?

One of my components is triggered by a conditional show: <app-list *ngIf="show"></app-list> At the same time, I emit an event in the same place where I activate this component: this.tabsEvens.emitMoveToVersions(version); this.router.navigate ...