Argument of type 'Response' is not assignable to parameter of type 'string'

OceanWavez picture OceanWavez · Oct 29, 2017 · Viewed 17.3k times · Source

I have this project I am working on. the idea is to retrieve books from google book API, using angular 4

I am struggling to understand how to read the JSON response, I am still learning Angular. I was searching the internet and found this source code on GitHub google bookstore

I am getting the following error

Argument of type 'Response' is not assignable to parameter of type 'string'.

for this line

  let bookResponse = JSON.parse(body);

I am not sure if I am doing it the correct way. appreciate your help

below is my method for send HTTP request.

  getBooks(searchparam: any){
let par = new HttpParams();
par.set('q', searchparam);

return this.httpClient.get('https://www.googleapis.com/books/v1/volumes', {
  params : new HttpParams().set('q',searchparam)
}).map(
  (response: Response) => {
    let data = response;

    return data;
  }
);

}

below is the method to get data from HTTP request and read JSON response

  getBook() {

const dataArrya = this.searchForm.get('param').value;

console.log(dataArrya);
this.requestService.getBooks(dataArrya)
  .subscribe(
    response  => {
      this.printData(response)
    //  console.log(this.bookData);
    },
    (error) => console.log(error)
  ); 

}

 private printData(res: Response) {

let body = res;
let books: Array<Book> = new Array<Book>();
let bookResponse = JSON.parse(body);
console.log(bookResponse);
console.dir(bookResponse);
for (let book of bookResponse.items) {
  books.push({
    title:book.volumeInfo.title,
    subTitle: book.volumeInfo.subTitle,
    categories: book.volumeInfo.categories,
    authors: book.volumeInfo.authors,
    rating: book.volumeInfo.rating,
    pageCount: book.volumeInfo.pageCount,
    image: book.volumeInfo.imageLinks === undefined ? '' : book.volumeInfo.imageLinks.thumbnail,
    description: book.volumeInfo.description,
    isbn: book.volumeInfo.industryIdentifiers,
    previewLink: book.volumeInfo.previewLink
  });
}

}

Answer

Michael Hulet picture Michael Hulet · Oct 29, 2017

JSON.parse takes a string, but you're passing it an Angular Response, which is an object (not a string). In order to convert an Angular Response to a string, you can call toString on it, like this:

let bookResponse = JSON.parse(body.toString());