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
- What am I missing or doing incorrectly?
- How can I go about resolving this issue effectively?