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
)
}
...