Currently, I've been involved in developing a Single Page Application using Angular 16, TypeScript, and The Movie Database (TMDB).
My task at hand is to implement the "infinite scroll" functionality on a particular component.
To achieve this, I have:
export class MoviesByGenre {
constructor(
private activatedRoute: ActivatedRoute,
private movieService: MovieService
) { }
public genreName: string | undefined = '';
public movieResponse!: MovieResponse;
public movies: Movie[] | undefined = [];
public genreResponse!: GenreResponse;
public genres: Genre[] | undefined = [];
public getMoviesByGenre(): void {
// Retrieving genre id from URL parameter
const genreId = Number(this.activatedRoute.snapshot.paramMap.get('id'));
const maxPage: number = 10;
let pageNumber: number = 1;
let isLoading: boolean = false;
// Fetching genre name from genres array
this.movieService.getAllMovieGenres().subscribe((response) => {
this.genreResponse = response;
this.genres = this.genreResponse.genres;
if (this.genres && this.genres.length) {
let currentGenre = this.genres.find(genre => genre.id === genreId);
if (currentGenre) {
this.genreName = currentGenre.name || '';
this.movieService.defaultTitle = this.genreName;
}
}
});
// Obtaining movies by genre id
this.movieService.getMoviesByGenre(genreId, pageNumber).subscribe((response) => {
this.movieResponse = response;
this.movies = this.movieResponse.results;
@HostListener('window:scroll', ['$event'])
onWindowScroll(event) {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight &&! isLoading) {
if (pageNumber < maxPage) {
isLoading = true;
// Appending to the movies array
this.movies?.push(...this.movies);
// Incrementing page number
pageNumber++;
isLoading = false;
}
}
}
})
}
ngOnInit() {
this.activatedRoute.params.subscribe(() => {
this.getMoviesByGenre();
});
}
ngOnDestroy() {
this.movieService.defaultTitle = '';
}
}
The Dilemma
I did not anticipate @HostListener
causing issues within my getMoviesByGenre()
method, but it indeed does.
An error is thrown as follows:
TS1146: Declaration expected.
@HostListener('window:scroll', ['$event'])
A demonstration has been set up with a stackblitz link here.
Inquiries
- What might be the flaw in my approach?
- Are there any suitable substitutes for utilizing
@HostListener
?