首页 > 解决方案 > Google 图书 api 返回错误类型错误:无法读取未定义 Angular 8 的属性“缩略图”

问题描述

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

它大部分工作正常,但对于某些搜索的标题,例如“neena”,它返回 TypeError: Cannot read property 'thumbnail' of undefined

我查看了控制台上的 http 响应,发现缺少一些书籍 books.volumeInfo.imageLinks 、 item.volumeInfo.imageLinks.thumbnail

我在这里看到了这个解决方案Google 图书 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>

我是 angular 8 的新手,我不知道如何以及在哪里使用 constpaidBooks = apiResponse.data.filter(book => book.listPrice) 根据解决方案

请有人帮助我

谢谢

标签: angularapiget

解决方案


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


推荐阅读