尝试从OMDb API获取数据,在Postman中结果返回正常,而getJSON函数返回非结构化数据
我已经尝试使用类型化接口
export interface ApiResponse {
Search: Movies[];
totalResults: string;
Response: string;
}
export interface Movies {
title: string;
year: number;
poster: string;
imdbId: string;
type: string;
}
这是getJSON代码
return getJSON<any>(
this.apiUrl + this.apiKey + "&s=Harry-potter&page10"
).then(r => {
console.log(r);
});
返回然后json格式错误
LOG from device : {
LOG from device : "imdbID": "tt1201607",
LOG from device : "Type": "movie",
LOG from device : "Poster": "https://m.media-amazon.com/images/M/MV5BMjIyZGU4YzUtNDkzYi00ZDRhLTljYzctYTMxMDQ4M2E0Y2YxXkEyXkFqcGdeQXVyNTIzOTk5ODM@._V1_SX300.jpg"
LOG from device : },
LOG from device : {
LOG from device : "Year": "2011",
LOG from device : "Search": [
LOG from device : "Title": "Harry Potter and the Deathly Hallows: Part 2",
LOG from device : {
LOG from device : "Title": "Harry Potter and the Sorcerer's Stone",
LOG from device : "Year": "2001",
LOG from device : "imdbID": "tt0241527",
LOG from device : "Type": "movie",
LOG from device : },
LOG from device : {
LOG from device : "Title": "Harry Potter and the Chamber of Secrets",
LOG from device : "Poster": "https://m.media-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
期望邮递员这样的回报:
{
"Search": [
{
"Title": "Harry Potter and the Deathly Hallows: Part 2",
"Year": "2011",
"imdbID": "tt1201607",
"Type": "movie",
"Poster": "https://m.media-amazon.com/images/M/MV5BMjIyZGU4YzUtNDkzYi00ZDRhLTljYzctYTMxMDQ4M2E0Y2YxXkEyXkFqcGdeQXVyNTIzOTk5ODM@._V1_SX300.jpg"
},
{
"Title": "Harry Potter and the Sorcerer's Stone",
"Year": "2001",
"imdbID": "tt0241527",
"Type": "movie",
"Poster": "https://m.media-amazon.com/images/M/MV5BNjQ3NWNlNmQtMTE5ZS00MDdmLTlkZjUtZTBlM2UxMGFiMTU3XkEyXkFqcGdeQXVyNjUwNzk3NDc@._V1_SX300.jpg"
},
{
"Title": "Harry Potter and the Chamber of Secrets",
"Year": "2002",
"imdbID": "tt0295297",
"Type": "movie",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTcxODgwMDkxNV5BMl5BanBnXkFtZTYwMDk2MDg3._V1_SX300.jpg"
}
],
"totalResults": "80",
"Response": "True"
}
答案 0 :(得分:0)
在console log
之前,请使用另一个then
(我很确定您应该有一个承诺),然后resolve
如下返回结果,或者以reject
返回错误。您还可以在catch块中添加console log
,以查看error
的正文:
return new Promise((resolve, reject) => {
fetch(
this.apiUrl + this.apiKey + "&s=Harry-potter&page10"
)
.then(res => res.json())
.then(r => {
console.log(r);
resolve(r)
})
.catch(err => reject(err))
})
fetch
方法已经返回了Promise
,因此您不必return a new Promise
就可以在.then()
之后串联fetch
。在我看来,使用resolve
和reject
更为合理。
这应该可以解决问题。
另请参见此处的本机脚本获取文档:Fetch