我在尝试在我的应用中绑定或显示某些数据时遇到问题。
我想这样做:
HTML:
<div *ngFor="let price of prices">
{{prices.Low}}
</div>
运行应用时出现此错误:
错误:无法找到不同的支持对象&#39; {&#34;成功&#34;:true,&#34;消息&#34;:&#34;&#34;,&#34;结果& #34;:[{&#34; MarketName&#34;:&#34; BTC-LTC&#34;&#34;高&#34;:0.01242&#34;低&#34;:0.01101255,&# 34;体积&#34;:125744.75175454,&#34;最后&#34;:0.01129999,&#34; BaseVolume&#34;:1456.43310343,&#34;时间戳&#34;:&#34; 2017-06-01T21: 49:12.573&#34;&#34;出价&#34;:0.01126674,&#34;向&#34;:0.0113,&#34; OpenBuyOrders&#34;:1390,&#34; OpenSellOrders&#34 ;: 3345&#34; PrevDay&#34;:0.01119779,&#34;创建&#34;:&#34; 2014-02-13T00:00:00&#34;}]}&#39;类型&#39;字符串&#39;。 NgFor仅支持绑定到Iterables,例如Arrays。
这是我的代码:
component.ts
import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { BittrexService } from '../bittrex/bittrex.service';
import {Observable} from "rxjs";
@Component({
selector: 'app-comprarmonedas',
templateUrl: './comprarmonedas.component.html',
styleUrls: ['./comprarmonedas.component.scss']
})
export class ComprarmonedasComponent implements OnInit {
prices: any;
constructor(private bittrexService: BittrexService) {
this.bittrexService = bittrexService;
}
ngOnInit(){
this.bittrexService.getPrices()
.subscribe(
data => this.prices = JSON.stringify(data)
);
}
}
` service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import {Observable} from "rxjs";
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import { MarketViewModel } from '../comprarmonedas/datosmoneda'
@Injectable()
export class BittrexService {
constructor(private http: Http, private marketModel : MarketViewModel) { }
public getPrices() :Observable<MarketViewModel> {
return this.http.get('https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-ltc')
.map((response: Response) => response.json());
}
}
Marketviewmodel:
export class MarketViewModel {
public success : boolean;
public message : string;
public result : MarketListObject[];
}
export class MarketListObject {
public MarketName : string;
public High : number;
public Low : number;
public Volume : number;
public Last : number;
public BaseVolume : number;
public TimeStamp : number;
public Bid : number;
public Ask : number;
public OpenBuyOrders : number;
public OpenSellOrders : number;
public PrevDay : number;
public Created : number;
}
答案 0 :(得分:0)
问题在于你是在尝试迭代一个字符串,而不是一个数组
在component.ts
中,您有以下代码行:
this.bittrexService.getPrices()
.subscribe(
data => this.prices = JSON.stringify(data)
);
而且我认为你的意思是这样做:
this.bittrexService.getPrices()
.subscribe(
data => this.prices = data.result
);
当您使用JSON.stringify
将数据转换为字符串时,ngFor
无法使用它,因为字符串不可迭代。相反,如果您返回data.result
,这是一个数组,ngFor
知道如何迭代它。
编辑:
正如yanbu在评论中指出的那样,你的模板中还有另一个错误。而不是:
<div *ngFor="let price of prices">
{{prices.Low}}
</div>
您需要使用:
<div *ngFor="let price of prices">
{{price.Low}}
</div>
这是因为价格是一个数组,它没有属性Low
,其中price是该数组的元素,应该包含属性Low
。