[英]Angular 6 API JSON ngFor Not Showing
我正在第一次使用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>
有誰知道通過* ngFor阻止CoinListings的顯示嗎? 還是給定結構,如何在HTML頁面中顯示每個CoinListing的變量?
如果我正確理解這一點,“每個條目都有一個變量鍵值,並與變量數組配對”,那么錢幣就是一個對象或數組。 如果是這樣的話
Found {{ coin }}
不會返回值。 您需要從硬幣內部調用變量。 例如,如果“ title”是硬幣內的鑰匙,那么您可以
Found {{ coin.title }}
您需要綁定屬性或使用json管道 {{_jsonData | json}}
{{_jsonData | json}}
之所以有效,是因為您要告訴綁定使用json管道賦予該結構
要了解有關JSON管道的更多信息: https : //angular.io/api/common/JsonPipe
你可以這樣做:
<p *ngFor="let coin of _jsonData">
Found {{ coin | json }}
<p>
或綁定要顯示的每個屬性
<p *ngFor="let coin of _jsonData">
Found:
{{ coin.Algorithm }}
{{ coin.BuiltOn }}
.
.
.
{{ coin.Url }}
<p>
更新:基於對象的結構
<div *ngFor="let coin of objectKeys(_jsonData)">
{{_jsonData[coin] | json}}
</div>
在您的ts文件中:
objectKeys(obj) {
return Object.keys(obj);
}
您需要使用如下所示的屬性
<p *ngFor="let coin of _jsonData">
Found {{ coin.Title }}
</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.