I am trying to add pagination to my Angular 10.1.0 project by slicing my data array. However, I get the TS2339: Property 'slice' does not exist on type 'WritableSignal<Data[]>'
error.
Here is an extraction of my component:
export class Component implements OnInit {
data = signal<Data[]>([]);
currentPage: number = 1;
constructor(private httoService: HttpService) {}
ngOnInit(): void {
this.fetchData();
}
fetchData(): void {
this.httpService.getData().subscribe((data) => {
this.data.set(data);
});
}
get paginatedData() {
const start = (this.currentPage - 1) * 100;
const end = start + 100;
return this.data.slice(start, end);
}
...
}
My http.service.ts:
export class HttpService {
http = inject(HttpClient);
private apiUrl = 'url'
getProducts(): Observable<Data[]> {
return this.http.get<Data[]>(this.apiUrl);
}
}
I have tried extracting the values before slicing:
const dataArray = Array.from(this.data().values)
but it returns 0.
We need to execute the signal, get the array and then slice
get paginatedData() {
const start = (this.currentPage - 1) * 100;
const end = start + 100;
return this.data().slice(start, end); // <- changed here!
}