add popular page logic + cach

This commit is contained in:
X4Lo committed 2024-04-01 21:24:59 +00:00
1 parent c001428bdf
commit c20b4d7fc1
1 file changed
+52 -5
@@ -1,4 +1,6 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { Entry } from '../../../shared/models/entry.model';
import { TmdbService } from '../../../core/services/tmdb.service';
@Component({ @Component({
selector: 'app-popular', selector: 'app-popular',
@@ -6,13 +8,58 @@ import { Component } from '@angular/core';
styleUrls: ['./popular.component.css'], styleUrls: ['./popular.component.css'],
}) })
export class PopularComponent { export class PopularComponent {
activeComponent: boolean = true; entryType: boolean = true;
entries: Entry[] = [];
showComponent(activeComponent: boolean) { pages: Record<string, Record<number, Entry[]>> = {
this.activeComponent = activeComponent; true: {},
false: {},
};
currentPage: number = 1;
constructor(private tmdbService: TmdbService) {}
ngOnInit() {
this.fetchEntries();
} }
getEndPoint(): string { setEntryType(entryType: boolean) {
return ''; this.entryType = entryType;
this.fetchEntries();
}
fetchEntries() {
if (this.pages[this.entryType.toString()][this.currentPage]) {
// ? not in cash > fetch entries from TMDB
this.entries = this.pages[this.entryType.toString()][this.currentPage];
} else {
// ? in cash > use cash entries
this.tmdbService
.getPopular(this.currentPage, this.entryType)
.subscribe((myEntries) => {
// * add fetched entries to the cash
this.pages[this.entryType.toString()][this.currentPage] = myEntries;
// * add fetched entries to the display list
this.entries =
this.pages[this.entryType.toString()][this.currentPage];
});
}
}
goToPage(page: number) {
this.currentPage = page;
this.fetchEntries();
}
get pageNumbers(): number[] {
this.currentPage = this.currentPage <= 0 ? 1 : this.currentPage; // page <= 0 fix
let startPage = this.currentPage <= 3 ? 1 : this.currentPage - 2;
let endPage = startPage + 4;
return Array.from(
{ length: endPage - startPage + 1 },
(_, i) => startPage + i
);
} }
} }