I am facing an issue while working with Angular and I am seeking a solution using Observables instead of Promises (async/await) which I am currently using.
The API endpoint allows sorting and pagination by passing parameters like pageSize and page to fetch the data. If no parameters are sent, it responds with a maximum of 1000 items. However, the total number of items can range from tens of thousands to just a few. The response from the API always follows this format:
{
items: [...], // (array of objects)
totalNumberOfItems: 123 // (total number of database entries)
}
Currently, my code looks something like this (without try-catches and unnecessary details), using Promises:
async getAllItems(): Promise<any[]> {
let page: number = 1;
let pageSize: number;
let items: any[] = [];
let totalNumberOfItems: number;
let initialResponse = await this.someService.getItems().toPromise();
items = [...items, ...initialResponse.items];
...
return items;
}
I am struggling to handle the Observable properly starting from the initial API call. I am considering something like this:
interface IResponse {
items: any[];
totalNumberOfItems: number;
}
getAllItems(): Observable<IResponse> {
let page: number = 1;
let pageSize: number;
let totalNumberOfItems: number;
return this.someService.getItems().pipe(
tap(res => {
...
})
// TODO: Need to figure out how to make subsequent calls iteratively and combine them with initial response
);
}
Edit: Following the suggested approach by thisdotutkarsh, I have made some modifications to my code and it seems to be working as expected:
getAllItems(): Observable<ItemsResponse> {
let page: number = 1;
let pageSize: number;
let totalNumberOfItems: number;
return this.service.getItems().pipe(
tap(response => {
...
}),
expand(response => {
...
}),
reduce((acc, response) => {
...
})
);
}