I am confused whether it's possible to make api call onInit component and evry time when parent gets event from child (pagination component), call api with new pageSize and pageNumber and assign this data. Main problem is that i want to avoid manually unsubscribe, and effect (beacuse it's not recomended to use it to change state).Maybe at this time there is no other option that unsubscribe. My next question is, is it more recommended to use a model instead of input and output signals?
child component ts
rows = input.required<number>();
pageChanged = output<number>();
onPageChange(event: PaginatorState) {
this.pageChanged.emit(event.rows!);
}
parent component html
<app-paginator
[rows]="pageSize()"
(pageChanged)="onPageChange($event)"
[totalRecords]="dataResponse()?.totalElements || 0"
[(paginationData)]="pagination"
[rowsPerPageOptions]="allowedNumbersOfRecordOnOnePage"></app-paginator>
parent component ts
pageNumber = signal<number>(0);
pageSize = signal<number>(100);
//apiService.getData(arg1,arg2) return observable
dataResponse= toSignal(
this.apiService.getData(this.pageNumber(), this.pageSize())
);
onPageChange(pageSize: number) {
this.pageSize.set(pageSize);
// How to set data to dataResponse reactively to signal without manually unsubscribe?
}
This will be more easy with the new resource API, but it's not there yet. It will be available as experimental in v19. Until then, you can convert your signals to Observables using toObservable()
, combineLatest()
to combine them and and switchMap()
to trigger the API request:
pageNumber = signal<number>(0);
pageSize = signal<number>(100);
data$ = combineLatest(
toObservable(this.pageNumber),
toObservable(this.pageSize)
).pipe(
switchMap(([pageNumber, pageSize]) =>
this.apiService.getData(pageNumber, pageSize)
),
);
dataResponse = toSignal(data$);
Note: Only use this approach if it's important that dataResponse
is a signal, for example if you are doing some additional computations on it. If you can work just with the Observable, check the other answer.