I have been working on an SPA with Angular 16, TypeScript and The Movie Database (TMDB).
I need to do an “infinite scroll” feature on one of the component.
For this purpose, 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 {
// Get 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;
// Get 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;
}
}
});
// Get 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;
// Push into the movies array
this.movies?.push(...this.movies);
// Increment page number
pageNumber++;
isLoading = false;
}
}
}
})
}
ngOnInit() {
this.activatedRoute.params.subscribe(() => {
this.getMoviesByGenre();
});
}
ngOnDestroy() {
this.movieService.defaultTitle = '';
}
}
The problem
I was not expecting @HostListener
to fail inside my getMoviesByGenre()
method, but it does.
It throws this error:
TS1146: Declaration expected.
@HostListener('window:scroll', ['$event'])
Questions
- What am I doing wrong?
- What is the easiest and most reliable way to fix this issue?