【发布时间】:2019-03-07 23:51:33
【问题描述】:
我第一次使用 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 的变量?
【问题讨论】:
-
您是否尝试过使用
{{_jsonData | json}}输出并查看结构中的所有内容是否正确? -
我已经有了,我尝试对 CoinListing 接口文件中的变量进行适当的排序。
标签: html json angular typescript angular6