【发布时间】:2019-05-06 22:06:36
【问题描述】:
我对前端开发完全陌生,并试图在 Angular 6 应用程序中显示 API 数据,但不知道该怎么做。
我可以在返回的详细信息的顶层显示值,但这是我正在努力解决的子级详细信息。
我正在使用一个使用路由的 Angular 6 应用程序。
下面是我的全部代码
Homepage.component.html
<h2>Book ID List</h2>
<button (click)="getBooks()">Get</button>
<div *ngFor="let book of books.items">
<p>ID: {{book.id}}</p>
</div>
我可以得到'ID'
我正在使用service 从测试API 中获取数据
Service.component.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiServiceService {
url = 'https://www.googleapis.com/books/v1/volumes?q=HTML5 Wire-frames';
constructor(private http: HttpClient) { }
private extractData(res: Response) {
const body = res;
return body || {};
}
getBooks(): Observable<any> {
return this.http.get(this.url).pipe(
map(this.extractData));
}
}
Homepage.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiServiceService } from '../../services/api-service.service';
@Component({
selector: 'app-homepage',
templateUrl: './homepage.component.html',
styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {
books: any = [];
constructor(private apiService: ApiServiceService) { }
ngOnInit() { }
getBooks() {
this.books = [];
this.apiService.getBooks().subscribe((data: {}) => {
console.log(data);
this.books = data;
});
}
}
目前返回如下:
我想要做的是显示“saleInfo”级别下的“eBook”中的值。我知道我需要为 HTML 中返回的每个 array 更改循环,但这是我卡住的地方。
我也不确定我拥有的代码是最好的,但它正在工作。正如我所说,我对这一切都是新手,并且可以从 API 中的顶级而非子级别提取值。
【问题讨论】:
-
如果要显示“isEbook”的值。只需使用
{{book.saleInfo.isEbook}} -
<p>ID: {{book.saleInfo.isEbook}}</p>呢? -
@SaddamPojee 您的建议不起作用,如果我将循环从
let book of books.items更新为let book of books然后将我的显示更新为ID: {{book.items.id}}或ID: {{book.items[0].id}}我收到以下错误Error: "Error trying to diff '[object Object]'. Only arrays and iterables are allowed" -
@OmurbekKadyrbekov 请看上面的回复
-
*ngFor 不适用于对象,它仅适用于数组和可迭代对象。
标签: arrays angular angular-services angular-components angular7