如何访问API调用中的所有数据

问题描述 投票:0回答:2

getNames(): Observable<bookmodel[]> {
  const endpoints = 'https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=xxxxxxxx';
  return this.http.get(endpoints).pipe(
        map(this.extractData));
 }
<h1 class="uk-flex uk-flex-center">Top Books{{bestsellers_date}}</h1>
<hr class="uk-divider-icon">
<div class="uk-child-width-1-5@s uk-grid-match" uk-grid>
    <div *ngFor="let name of names;  let i = index">
        <div class="uk-card uk-card-hover uk-card-body">
            <h3 class="uk-card-title">{{name.title}}</h3>
            <img style="height:250px;" src="{{name.book_image}}"><br/><br/>
            <span>Summary: {{name.description || ' NA' |characters:150}}</span><br />
            <hr class="uk-divider-icon">
            <span>Author {{name.author}}</span>
            <br/>
            <br/>Best Sellers Rank {{name.rank}}
            <br />
            <span>Weeks on List {{name.weeks_on_list}}</span>
            <div class="uk-card-footer">
                <span><a  class="uk-button uk-button-primary" href="{{name.amazon_product_url}}">Buy On Amazon</a></span>
            </div>
        </div>
    </div>
</div>
Okay so the code above makes a call to the api and the api returns an object with nested arrays in order to get the infomation I want Ive put defined the data as data.results.books but theres data that I want to access in the data.results Ive tryed just taking the .books part out but the the NGFOR doesn't work with objects is there a way to store or even get the data in data.results and how would I store it
html angular
2个回答
2
投票

service.ts

getNames(): Observable<bookmodel[]> {
  const endpoints = 'https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=7W3E72BGAxGLOHlX9Oe2GQSOtCtRJXAt';
  return this.http.get<bookmodel[]>(endpoints);
 }

component.ts

this.service.getNames().subscribe(names =>  this.names = names);

HTML

<div *ngFor="let name of names;  let i = index"> 
......
</div>

如果您没有订阅它,请在html中使用async pipe

<div *ngFor="let name of names | async;  let i = index"> 
    ......
</div>

1
投票

尝试使用异步管道更新*ngFor。您需要使用async管道,因为httpClient始终返回Observable。

<div *ngFor="let name of names | async; let i = index"></div>

同时更新getNames并从那里删除.pipe

getNames(): Observable<bookmodel[]> {
  const endpoints = 'https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=7W3E72BGAxGLOHlX9Oe2GQSOtCtRJXAt';
  return this.http.get<bookmodel[]>(endpoints);
 }
© www.soinside.com 2019 - 2024. All rights reserved.