Google 图书 api 返回错误类型错误:无法读取未定义的 Angular 8 的属性"缩略图"



我正在制作简单的角度Web应用程序,用户可以在其中搜索书籍并返回不同的书籍。

它基本上工作正常,但对于搜索的某些标题,例如"neena",它返回类型错误:无法读取未定义的属性"缩略图">

我在控制台上查看了http响应,并找到了一些书籍书籍.volumeInfo.imageLinks,item.volumeInfo.imageLinks.thumbnail丢失了

。我在这里看到了这个解决方案 谷歌图书 api 返回缺少的参数,但不知道如何在我的应用程序中使用它。

服务.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
import 'rxjs/Rx';

@Injectable({
providedIn: 'root'
})
export class GoogleapiService {
API_KEY = 'AIzaSyDHDCI5JYsbDRGRa5nx252a0kv43XwCpvE';
constructor(private httpClient: HttpClient) { }
getNews(searchText):Observable<any>{
const encodedURI = encodeURI("https://www.googleapis.com/books/v1/volumes?q="+searchText+"&maxResults=12&key=");
return this.httpClient.get(encodedURI);
} 
}

组件.ts

import { Component, OnInit } from '@angular/core';
import {GoogleapiService} from '../services/googleapi.service';
import { NgForm } from '@angular/forms';
import {Books} from '../booksearch/books';

@Component({
selector: 'app-booksearch',
templateUrl: './booksearch.component.html',
styleUrls: ['./booksearch.component.css']
})
export class BooksearchComponent implements OnInit {
items;
searchText;
constructor(private googleapiservice: GoogleapiService) { }
ngOnInit() { 
}
onSubmit(form:NgForm){
this.searchText = form.value.searchVariable;
this.googleapiservice.getNews(form.value.searchVariable).subscribe((data)=>{
this.items = data['items'];
console.log(data);
//console.log("test");
//console.log(this.items[1].volumeInfo.imageLinks.thumbnail);
//console.log(form.value.searchVariable);
});
}  
}

组件.html

<h1>BOOKS</h1>
<div class="container">
<h1>search your books</h1>
<form #searchForm="ngForm" (ngSubmit)="onSubmit(searchForm)">
<div class="form-group">
<input type="text" class="form-control mt-10" name="searchVariable" placeholder="search for books" autocomplete="off" ngModel/>
</div>
<button type="submit" class="btn btn-danger"> Search</button>
</form>
</div>   
<div *ngFor="let item of items">
<h2>{{item?.volumeInfo.title}}</h2>
<p>{{item?.volumeInfo.authors}}</p>
<p>{{item?.volumeInfo.description}}</p>
<p>{{item.volumeInfo.imageLinks?.thumbnail}}</p>
<img src={{item.volumeInfo.imageLinks.thumbnail}} alt="Smiley face" height="42" width="42">
</div>

我是角度 8 的新手,我不知道如何以及在哪里使用常量付费书籍 = apiResponse.data.filter(book => book.listPrice( 根据解决方案

请有人帮助我

谢谢

问题出在组件.html行中,您有 {{item.volumeInfo.imageLinks.thumbnail}} imageLinks是未定义的,您无法获取未定义的缩略图。在获得缩略图之前,您必须检查 item.volumeInfo.imageLinks != 未定义。

最新更新