Using Angular routing, in the component's ngOnInit
method, I retrieve a genre ID through an observable. Within this observable, a service method is called that makes an HTTP request.
this.movies: Movie[];
ngOnInit() {
this.route.paramMap.subscribe(param => {
let id = +param.get('id');
this.movieService.getMoviesByGenres(id).subscribe( response => {
this.movies = response['results'];
});
});
}
The resulting data looks like this:
"results": [
{
"vote_count": 664,
"id": 287947,
"video": false,
"vote_average": 7.4,
"title": "Shazam!",
.
.
.
},
{
"vote_count": 3623,
"id": 299537,
"video": false,
"vote_average": 7.2,
"title": "Captain Marvel",
.
.
.
}, ...
]
However, the movies returned do not include cast information. To fetch the casts for each movie, an additional HTTP request needs to be made for each movie and the cast details need to be added to the movies[i].cast
array.
Therefore, the desired functionality can be achieved as follows:
ngOnInit() {
this.route.paramMap.subscribe(param => {
let id = +param.get('id');
this.movieService.getMoviesByGenres(id).subscribe( response => {
this.movies = response['results'];
//pseudo code
foreach(this.movies as movie) {
this.movies[current element].casts =
this.movieService.getCastByMovieId(movie.id);
}
});
});
}
This means getting movies by genre, then iterating through the movies[]
array upon receiving the results. For each movie, call a method to get the cast based on the movie ID and add the casts to the movie's casts: string []
property. Finally, return this.movies: Movies[]
which now includes the cast information as well.