0

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!

Corey Sutton
  • 767
  • 5
  • 19

1 Answers1

0

Each time you call nextPage() you subscribe again. you can store the google subscribe in Subscription object from the rxjs library the if Subscription is not undefined, unsubscribe and subscribe again. you can check what happens by starting intervals

fetchProducts(category) {
  if (this.productsSub != undefined)
    this.productsSub.unsubscribe();
  let productsList: {[key: string]:ProductData} = {};
  const snapshot = this.db.collection(category).get();
  this.productsSub = snapshot.subscribe(data => {
    data.forEach( doc => {
      console.log(doc.id)
      let product: ProductData = doc.data() as ProductData;
      productsList[doc.id] = product;
   }, e => {
           console.log(e);
      });

    //Update the list
    this.products = productsList;
    //Stream the list
    this.productsList.next(productsList);
    console.log(productsList);
  });
}

this is how I fetch data from firebase, productsSub is Subscription Object

  • Unfortunately this did not work. – Corey Sutton Jul 31 '23 at 23:26
  • just check the api, https://www.googleapis.com/books/v1/volumes?q=harry&startIndex=50&maxResults=40&key={myapi} this is not code mistake, there is something with the google api works, I`m still trying to figure it out, and yet don`t subscribe multiple time your Observable, consider what I posted. I will update if I could solve the total items problem my self – Ohad Cochavi Aug 01 '23 at 02:18