Angular return 我是一个未定义的数组,但我之前定义过

Angular return me an Array as undefined, but I had defined previously

我正在尝试使用 Google 本书 API。首先,我创建了可以正常工作的接口,然后我创建了一个方法,该方法 return 我是一个包含书籍列表的数组。


    public getBooks(): Observable<Book[]>{
        return this.http.get<Book[]>('https://www.googleapis.com/books/v1/volumes?q=filibusterismo');
    
      }

(我添加了我要搜索的元素“filibusterismo”,以避免出错,但我稍后会更改。)

然后,我想使用书籍数组,但我不能使用 ngFor 循环,因为 getBook return 我是一个可观察的书籍数组,而不是书籍数组。这是我原来的构造函数


   books:Book[];
     constructor(private GoodreadsService:GoodreadsService) { }
   
     ngOnInit() {
      this.libro=this.GoodreadsService.getBooks();
   }

我曾尝试使用异步解决此问题。

*ngFor="let book of books | async"

但是我也遇到了同样的问题。所以在 SO 中阅读 post 我了解到我必须在 ngOnInit() 中使用订阅,就像这样。


     this.GoodreadsService.getBooks().subscribe(res=>{this.books=res},
          error => { // on failure
            console.log('Error Occurred:');
          });

问题是,虽然我没有 return 任何类型的错误,但如果我写

console.log(this.libro1);

控制台说数组是未定义的,而我已经将它定义为Book的数组。此外,我仍然不能使用 ngFor。

我也曾尝试映射 getBook 方法,以便 return 我是一个数组而不是一个可观察的数组,但尽管在 SO 中阅读了很多问题,我还是无法做到。

所以,有人能告诉我如何解决这个问题,以便我可以在 HTML 中使用 ngFor 吗?

我的HTML是这个


    <p>busqueda works!ss </p>
    <table>
      <thead>
          <th>Name</th>
          <th>Indexs</th>
      </thead>
      <tbody>
        <div *ngFor="let book of books | async">
            <h1  >
                <p>prueba</p>
            </h1>
          </div>
      </tbody>
    </table>

这是您需要执行的操作。初始化 API 调用并相应地订阅以发送请求。返回响应后,遍历其上的项目。

Please refer to the working sample stackblitz attached here.

示例 component.ts :

import { Component, OnInit } from "@angular/core";
import { SampleService } from "./sample.service";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  books: any;
  constructor(public sample: SampleService) {}
  ngOnInit() {
    this.sample.getBooks().subscribe(data => {
      console.log(data.items)
      this.books = data.items;
    });
  }
}

示例 HTML :

<table>
    <thead>
    </thead>
    <tbody>
        <div *ngFor="let book of books">
            <h4>
                <p>kind : {{book.kind}}</p>
        <p>Id : {{book.id}}</p>
        <p>etag : {{book.etag}}</p>
            </h4>
        </div>
    </tbody>
</table>