我正在尝试创建一个从端点返回的数据列表,我得到了 10 位数据,我想使用 *ngFor 来显示它们。我已经在正确的时间正确输入了数据,但它说
错误错误:“找不到类型为'object'的不同支持对象'[object Promise]'。NgFor 仅支持绑定到Iterables,例如数组。”
但是,据我所见,您可以在最新版本的 Angular 中在 *ngFor 中使用 json。
JSON 返回:https ://pastebin.com/TTn0EqSS
app.component.html
<div [class.app-dark-theme]="true">
<mat-sidenav-container fullscreen class="sidenav-container">
<mat-toolbar class="toolbar">
Coin Market Cap 3rd party api app
</mat-toolbar>
<mat-card>
<mat-card-header>
<mat-card-title>CryptoCurrency Market Overview</mat-card-title>
<mat-card-subtitle>Top 15 current currencies.</mat-card-subtitle>
</mat-card-header>
<mat-card-content class="currency-listings">
<div *ngIf="finishedLoading">
<mat-grid-list cols="1" rowHeight="2:1">
<mat-grid-tile *ngFor="let currency of currenciesJson; let i = index" (click)="selectCurrency(i)">
{{currency.data[i].name}}
</mat-grid-tile>
</mat-grid-list>
test
test
test
</div>
</mat-card-content>
</mat-card>
<!-- (click)="showInfo(true)" -->
<mat-card *ngIf="displayInfo">
test
</mat-card>
</mat-sidenav-container>
</div>
coin-market-cap.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class CoinMarketCapService
{
key = "REDACTED";
apiUrl = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/';
constructor(public http: HttpClient) { }
getCurrencies(totalCurrencies: number)
{
let promise = new Promise((resolve, reject) => {
let url = this.apiUrl + "listings/latest?limit=" + totalCurrencies + "&CMC_PRO_API_KEY=" + this.key;
this.http.get(url)
.toPromise()
.then(
res => {
console.log(res);
resolve();
});
})
return promise;
}
getCurrency(currencyId: number)
{
console.log("in getcurrency");
let url = this.apiUrl + "info?id=" + currencyId + "&CMC_PRO_API_KEY=" + this.key;
console.log(url);
return this.http.get(url);
}
}
app.component.ts
import { Component } from '@angular/core';
import { CoinMarketCapService } from '../services/coin-market-cap.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
currenciesJson = {};
displayInfo = false;
finishedLoading = false;
constructor(private CoinMarketCapService: CoinMarketCapService) {}
ngOnInit()
{
console.log(this.currenciesJson);
this.currenciesJson = this.CoinMarketCapService.getCurrencies(10)
.then(res =>
this.finishedLoading = true
)
console.log(this.currenciesJson);
console.log("exiting ngoninit");
}
selectCurrency(currencyId: number)
{
console.log(currencyId);
let currencyObject = this.CoinMarketCapService.getCurrency(currencyId);
}
showInfo ( showInfo: boolean )
{
this.displayInfo = showInfo;
}
}