【问题标题】:I can use an interface in the html component but not in the typescript我可以在 html 组件中使用接口,但不能在打字稿中使用
【发布时间】:2021-03-17 15:48:00
【问题描述】:

我在 Angular 中使用 Google Books Api。为此我创建了以下界面


    export interface DateBooks {
    kind:string,
    totalItems:number,
    items:Book[]
   }
   export interface Book {
   kind:string,
   id:string,
   etag:string,
   selfLink:string,
   volumeInfo: VolumeInfo[],
   saleInfo:SaleInfo,
   accessInfo:AccessInfo,
   searchInfo:SearchInfo
   }
   export interface VolumeInfo {
   title:string,
   subtitle:string,
   authors:string[],
   publisher:string,
   publisedDate:string,
   description:string,
   industryIdentifiers:IndustryIdentifiers[],
   readingModes:ReadingModes,
   pageCount:number,
   printType:string,
   categories:string[],
   maturityRating:string,
   allowAnonLogging:boolean,
   contentVersion:string,
   panelizationSummary:PanelizationSummary,
   averageRating:number,
   ratingCount:number,
   imageLinks:ImageLinks,
   language:string,
   previewLink:string,
   infoLink:string,
   canonicalVolumeLink:string
   }
   
   export interface ImageLinks {
   smallThumbnail:string,
   thumbnail:string
   }
   
   
   export interface IndustryIdentifiers{
       type:string,
       identifier:string
   }
   
   export interface ReadingModes{
       text:boolean,
       image:boolean
   }
   
   export interface PanelizationSummary{
       containsEpubBubbles:boolean,
       containsImageBubbles:boolean
   }
   
   export interface SaleInfo{
       country:string,
       saleability:string,
       isEbook:boolean
   }
   
   export interface AccessInfo{
       country:string,
       viewability:string,
       embeddable:boolean,
       publicDomain:boolean,
       textToSpeechPermission:string,
       epub:Epub,
       pdf:Pdf,
       webReaderLink:string,
       accessViewStatus:string,
       quoteSharingAllowed:boolean
   }
   
   export interface SearchInfo{
       textSnippet:string
   }
   
   export interface Epub{
       isAvailable:boolean
   }
   
   export interface Pdf{
       isAvailable:boolean
   }

这是我的打字稿组件


    databooks:DateBooks;
    books:Book[];
    title:string;
    constructor(private GoodreadsService:GoodreadsService) { }
    
      ngOnInit(): void {
      }
    
    getLibros(libro:string){
      this.GoodreadsService.getBooks(libro).subscribe(data=>{
        this.databooks=data;
        this.books=this.databooks.items;
      })
    
        }

这个,getBooks 方法


public getBooks(busqueda:string): Observable<DateBooks>{
    return this.http.get<DateBooks>(`https://www.googleapis.com/books/v1/volumes?q=${busqueda}&maxResults=40`);

还有,这是 html 组件


    <input type="text" id="namea" name="nameb" required
        minlength="4" maxlength="8" size="10" placeholder="introduzca texto" [(ngModel)]="title" (keyup)="getLibros(title) " >
        <div *ngFor="let book of books">
          <h4 class="prueba">
              <p> {{book.volumeInfo['title']}}</p>
       <p><img src={{book.volumeInfo.imageLinks.thumbnail}}></p>
          </h4>    
        </div>

所以,我可以在 html 中毫无问题地使用该界面,此外,如果我在输入中运行并编写任何内容,页面会正确显示书籍的标题和封面。但是,我不能只获取 ts 上接口的几个属性。例如,订阅数据是getBooks返回的对象,我可以毫无问题地使用data.items,但是如果我写data.item.volumeInfo可视代码说这个错误:Property 'volumeinfo' does not exist on type 'Book []',但我可以在 html 中毫无问题地使用,我不知道如何解决这个问题?。

谁能告诉我是什么问题或我的错误?

【问题讨论】:

    标签: html angular typescript api interface


    【解决方案1】:

    问题 #1 - “但是如果我写 data.item.volumeInfo 可视化代码说这个错误:Property 'volumeinfo' does not exist on type 'Book[]'”

    • 那是因为您试图直接在 array 书籍中访问 object property

    • 例子:

    // Mock Data
    const books: Books[] = [ 
       { name: 'Book 1', volumeInfo: '123' }, 
       { name: 'Book 2', volumeInfo: '457' } 
    ];
    
    // This is what you are trying to do which will produce an error
    // Directly accessing a property inside an array which is invalid since we are not accessing
    // a mere object but we are accessing an array of object
    books.volumeInfo
    
    // What we must do to access them is through:
    books[0].volumeInfo
    
    // or through using .map, .filter, .forEach and other similar to iterate the array and access the properties inside
    books.map(book => console.log(book))
    books.forEach(book => console.log(book));
    

    关注 #2 - 但我可以在 html 中毫无问题地使用

    • 那是因为您已经通过 *ngFor="let book of books" 迭代了数组,就像我们可以通过 .map, .filter, and .forEach 迭代对象数组一样

    • 类似于:

    books.forEach(book => console.log(book.volumeInfo));        // 123
                                                                // 457
    

    总而言之,如果我们想访问一个对象数组,请使用.map, .filter, .forEach or other similar 来获取该数组下所有属性的实例

    【讨论】:

    • 您的解释已经很清楚了,非常感谢:)
    猜你喜欢
    • 2021-10-10
    • 2014-07-31
    • 2018-05-31
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2016-06-03
    • 2021-02-15
    相关资源
    最近更新 更多