Arrays Angular返回一个未定义的数组,但我以前定义过
我正在尝试使用谷歌图书API。首先我创建了工作正常的接口,然后我创建了一个方法,该方法返回一个包含书籍列表的数组Arrays Angular返回一个未定义的数组,但我以前定义过,arrays,angular,typescript,undefined,subscribe,Arrays,Angular,Typescript,Undefined,Subscribe,我正在尝试使用谷歌图书API。首先我创建了工作正常的接口,然后我创建了一个方法,该方法返回一个包含书籍列表的数组 public getBooks(): Observable<Book[]>{ return this.http.get<Book[]>('https://www.googleapis.com/books/v1/volumes?q=filibusterismo'); } 我曾尝试使用async修复此问题 *ng
public getBooks(): Observable<Book[]>{
return this.http.get<Book[]>('https://www.googleapis.com/books/v1/volumes?q=filibusterismo');
}
我曾尝试使用async修复此问题
*ngFor=“让书籍之书|异步”
但我也有同样的问题。因此,在阅读中,我学会了在ngOnInit()中使用subscribe,如下所示
this.GoodreadsService.getBooks().subscribe(res=>{this.books=res},
error => { // on failure
console.log('Error Occurred:');
});
问题是,尽管我没有返回任何类型的错误,但如果我写
console.log(this.libro1)代码>
控制台说数组是未定义的,而我将它定义为Book数组。此外,我仍然不能使用ngFor
我还尝试映射getBook方法,以便返回一个数组而不是一个可观察的数组,但尽管我读了很多这方面的问题,我还是做不到
那么,有人能告诉我如何解决这个问题,以便在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调用并相应地订阅以发送请求。返回响应后,在响应上迭代项目
请参考随附的stackblitz工作样本
示例组件。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;
});
}
}
<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>
示例HTML:
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;
});
}
}
<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>
种类:{{book.kind}
Id:{{book.Id}
etag:{{book.etag}
您可以尝试在构造函数中使用subscribe
方法吗?使用|async
或。subscribe
是如何从可观察到的ngFor
循环中获取值的方法。不清楚您一直试图控制台的位置。记录值时不带a。这是否回答了您的问题?我想不会,但也许我得多学点。非常感谢:)谢谢,但如果我写data.items,它会返回一个错误,告诉我书中不存在项(这是真的)。如果我尝试输入一个Book参数,比如kind,它也会返回一个错误。根据需要更新books模型,它会得到解决。你能把它标为正确答案吗。非常感谢