I am working on an asp.net application that uses the Google Books API. I am using the API to return a list of books based on a search query.
public async Task<BookSearchResponseModel> SearchBooks(string query, int startIndex = 0, int maxResults = 10)
{
var response = await _client.GetAsync($"https://www.googleapis.com/books/v1/volumes?q={query}&startIndex={startIndex}&maxResults={maxResults}&key={_apiKey}");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
//return data;
return JsonConvert.DeserializeObject<BookSearchResponseModel>(content);
}
Controller:
[HttpGet("search")]
public async Task<IActionResult> SearchBooks(string query, int startIndex = 0, int maxResults = 10)
{
var results = await _googleBooksService.SearchBooks(query, startIndex, maxResults);
return Ok(results);
}
This search query is then being paginated in the angular app.
Angular Service:
getBooks(query: string, startIndex: number = 0, pageSize: number = 10): Observable<BookSearchResponseModel> {
const params = new HttpParams()
.set('query', query)
.set('startIndex', startIndex.toString())
.set('maxResults', pageSize.toString())
return this.http.get<BookSearchResponseModel>(this.searchUrl, { params: params }).pipe(
catchError((error) => {
console.error("Error retrieving books: ", error);
return throwError(error);
})
)
}
Component:
updatePage() {
this.googleBooksService.getBooks(this.query, this.pageIndex * 10, this.pageSize)
.subscribe((data: BookSearchResponseModel) => {
if (data && data.items) {
this.searchResults = data.items;
console.log('Total items from API', data.totalItems)
this.totalPages = Math.ceil(data.totalItems / this.pageSize);
}
})
}
prevPage() {
if (this.pageIndex > 0) {
this.pageIndex--;
this.updatePage();
}
}
nextPage() {
this.pageIndex++;
this.updatePage();
}
The issue I am having is that whenever I hit "next page" the number of "totalItems" from the API jumps, when it should be the same.
For example, a search query of "Brandon Sanderson" has an initial return of "totalItems": 2809. When I hit "next page", the total number of items is "totalItems: 4051".
Please help!