ngFor没有从数组对象获取任何数据

时间:2020-08-18 13:30:12

标签: javascript angular api

ngFor不显示项目。是否是因为下面的值刚刚在控制台中被评估错误?有什么办法解决吗?

获取数据的服务:

  getBooks(id) {
    return this.httpClient.get(
      `${this.BooksApiService.baseUrlBooks}detail/${id}/`,
      {
        headers: this.headers,
      }
    );
  }

组件:

  books: any = [];
  bookId : any;

ngOnInit() : void {
    this.route.paramMap.subscribe(params => {
      this.booksId = params.get('detail')
    })

    this.getBooks(this.bookId).subscribe(books => {
      this.books.push(books)
    });
    console.log(this.books)
  }

模板:

<div *ngFor="let book of books">
    <div *ngFor="let result of book.results">
        <h3>{{result.id}}</h3>
    </div>
</div>

来自http:// localhost:8000 / api / books / detail / 1 [params url] /

的Postman JSON
{
    "message": "Visit Added",
    "results": {
        "user": {
            "id": 1,
            "username": "imboyo"
        },
        "id": 1,
        "title": "A Story About a Grandpa and Grandma Who Returned Back to Their Youth",
        "alternative_titles": [],
        "artist": [
            {
                "id": 1,
                "name": "Araido Kagiri"
            }
        ],
    ...
}

My Console Log from console.log(this.books) in component

2 个答案:

答案 0 :(得分:1)

要从Angular的Api中获取数据

Servie.ts

import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Http, Headers, Response } from '@angular/http';
import { environment } from '../../../environments/environment';

@Injectable({
    providedIn: 'root'
})
export class Service {

    constructor(private http: Http) { }


 GetData() {
        return this.http.get('APIURL').pipe(map((response: any) => response.json()));
    }

组件

    public APIDATA : string;
    ngOnInit(){
        this.Service.GetData().subscribe((res) => {
           console.log(res);
           this.APIDATA = res;           
        }
      }

HTML

<div *ngFor="let data of APIDATA">
    <div>
        <h3>{{data}}</h3>
    </div>
</div>

答案 1 :(得分:1)

我认为这只是时间问题。您能否重新组织下面的代码,如果能解决您的问题,请告诉我。

方法1:

.ts

 books: any = [];
  bookId : any;

ngOnInit() : void {
    this.route.paramMap.subscribe(params => {
      this.booksId = params.get('detail');
      this.getBooks(this.bookId).subscribe(books => {
         this.books.push(books);
         console.log(this.books);
      });
    });
  }

.html

从提供的图像中,结果不是数组,而是一个对象。因此,如下更改HTML。

<div *ngIf="books && books.length > 0>
     <div *ngFor="let book of books">
            <h3>{{book.result.id}}</h3>
    </div>
</div>

说明:

打字稿文件中的第一件事,我们不能说在进行API调用之前booksId是否获得了值,所以我已经进行了重组,因为只有在获得booksId值之后才执行API调用。

在HTML中,仅当数组长度大于0时,才可以渲染到DOM中。由于角度变化检测机制,您将收到“刚刚评估了下面的值”。

参考https://ionic-framework.programmingpedia.net/en/knowledge-base/45496171/cannot-get-the-data-due-to--value-below-was-evaluated-just-now-

how to fix "value below was evaluated just now" in angular 7

方法2:

您能否使用JSON.stringify如下所示尝试console.log。

.ts

 books: any = [];
 bookId : any;

ngOnInit() : void {
    this.route.paramMap.subscribe(params => {
      this.booksId = params.get('detail');
      this.getBooks(this.bookId).subscribe(books => {
         this.books.push(books);
         console.log(JSON.stringify(this.books, null, 2));
      });
    });
  }

参考:https://medium.com/@decker/javascript-developer-console-fe6fa491654a