I have this service that calls to an API to get a bunch of movie descriptions and returns an Observable:
getNowPlayingMovies$(page: number, country?: string): Observable<NowPlaying> {
console.log(`${this.baseUrl}${this.now_playing}?${this.key}®ion=${country || 'US'}&page=${page}`);
return this.http.get<NowPlaying>(
`${this.baseUrl}${this.now_playing}?${this.key}®ion=${country || 'US'}&page=${page}`
);
}
On the component that uses this function above I call it changing every time the page value so I can offer to the user pagination on the component view.
And this is the component that calls the service:
getNowPlayingMovies(): void {
this.nowPlayingService.getNowPlayingMovies$(this.page).subscribe((data) => {
this.nowPlaying.push(
...data.results.filter((result) => result.backdrop_path)
);
if(!this.last_page){
this.last_page = data.total_pages
this.page++;
} else if(this.page <= data.total_pages) {
this.page++;
}
console.log(data);
console.log(this.nowPlaying);
});
}
I've read that on Angular you should always try to work using Observable rather than Promises but on scenarios like this I don't see any advantage of subscribing to the api call response.
It would be correct to transform the Observable in the service to a Promise like this?
getNowPlayingMovies$(page: number, country?: string): Promise<NowPlaying> {
console.log(`${this.baseUrl}${this.now_playing}?${this.key}®ion=${country || 'US'}&page=${page}`);
return this.http.get<NowPlaying>(
`${this.baseUrl}${this.now_playing}?${this.key}®ion=${country || 'US'}&page=${page}`
).toPromise();
}
I'm learning Angular and I'm working this to add it to my portfolio so I want to learn to do it the right way and the best way possible.