“响应"类型的参数不能分配给“字符串"类型的参数
我正在从事这个项目. 这个想法是使用angular 4从Google book API检索图书
I have this project I am working on. the idea is to retrieve books from google book API, using angular 4
我正在努力了解如何读取JSON响应,但我仍在学习Angular. 我正在互联网上搜索,并在GitHub上找到了此源代码 Google书店
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
我遇到以下错误
Argument of type 'Response' is not assignable to parameter of type 'string'.
此行
let bookResponse = JSON.parse(body);
我不确定我是否以正确的方式进行操作. 感谢您的帮助
I am not sure if I am doing it the correct way. appreciate your help
下面是我发送HTTP请求的方法.
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;
}
);
}
下面是从HTTP请求获取数据并读取JSON响应的方法
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
});
}
}
JSON.parse
需要一个字符串,但是您要向它传递一个Angular Response
,它是一个对象(不是字符串).为了将Angular Response
转换为字符串,可以在其上调用toString
,如下所示:
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());