首页 > 解决方案 > Angular 6 API JSON ngFor不显示

问题描述

我正在第一次使用 Angular 6 开发一个项目,我正在创建一个从在线 URL 获取 JSON 数据的应用程序,并在 HTML 页面上列出每个条目。每个条目都有一个变量键值,与变量数组配对。问题是,尽管没有显示任何错误,*ngFor 语句没有显示任何条目,但 {{ jsonData | json }} 表示数据返回成功。这是我的代码。

api-retrieval-service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpResponse} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { CoinListing } from './coinListing';

@Injectable({
  providedIn: 'root'
})
export class ApiRetrievalService {
  constructor(private _http: HttpClient) { }

  coinList() {
    return this._http.get('https://min-api.cryptocompare.com/data/all/coinlist').pipe(catchError(this.errorHandler));
  }

  errorHandler(error: HttpErrorResponse) {
     return throwError(error);
  }
} 

coinlist.component.ts

import { Component, OnInit } from '@angular/core';
import { ApiRetrievalService } from '../api-retrieval.service';
import { CoinListing } from '../coinListing';

@Component({
  selector: 'app-coinlist',
  templateUrl: './coinlist.component.html',
  styles: []
})
export class CoinlistComponent implements OnInit {
  title = 'Coin Listing';
  public _jsonData:CoinListing[] = [];
  constructor(private _apiRetrieval: ApiRetrievalService) { }
  ngOnInit() {
    this._apiRetrieval.coinList()
      .subscribe(
        result =>  {
          this._jsonData = result.Data;
          console.log('Success', result.Data);
        },
        error => this.errorMsg = error.statusText
     );
  }
}

coinListing.ts

export interface CoinListing {
  [key:string]: {
    Algorithm: string;
    BuiltOn: string;
    CoinName: string;
    FullName: string;
    FullyPremined: string;
    Id: string;
    ImageUrl: string;
    IsTrading: string;
    Name: string;
    PreMinedValue: string;
    ProofType: string;
    SmartContractAddress: string;
    SortOrder: string;
    Sponsored: string;
    Symbol: string;
    TotalCoinSupply: string;
    TotalCoinsFreeFloat: string;
    Url: string;
  }
};

coinlist.component.html

<div style="text-align:center">
  <h1>
    {{ title }}
  </h1>
</div>
<br/>
<p *ngFor="let coin of _jsonData">
 Found {{ coin }}
</p>

任何人都知道是什么阻止了 CoinListings 通过 *ngFor 显示?或者,给定它们的结构,我如何在 HTML 页面中显示每个 CoinListing 的变量?

标签: htmljsonangulartypescriptangular6

解决方案


如果我理解正确,“每个条目都有一个变量键值,与变量数组配对”,那么硬币就是一个对象或数组。如果是这样的话

Found {{ coin }} 

不会返回值。您需要从硬币内部调用一个变量。例如,如果“标题”是硬币内的一个键,那么你可以这样做

Found {{ coin.title }}

推荐阅读