【发布时间】:2017-11-18 08:17:58
【问题描述】:
我正在尝试在 dom 中显示一些信息,但出现此错误:
错误:尝试区分“[object Object]”时出错
我试图做的是从https://www.surbtc.com/api/v2/markets/btc-clp/ticker 迭代这些数据:
{"ticker":{"last_price":["1771455.0","CLP"],"min_ask":["1771432.0","CLP"],"max_bid":["1660003.0","CLP"] ,"volume":["178.37375119","BTC"],"price_variation_24h":"-0.107","price_variation_7d":"-0.115"}}
我想在 html 中这样显示:
<div *ngFor="let price of prices">
{{price.min_ask}}
</div>
这是 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 { SurbtcMarket } from './surbtcmarket'
@Injectable()
export class SurbtcService {
constructor(private http: Http, private surBtcMarket : SurbtcMarket) { }
public getPricess() :Observable<SurbtcMarket> {
return this.http.get('https://www.surbtc.com/api/v2/markets/btc-clp/ticker')
.map((response: Response) => response.json());
}
}
接口 surbtcmarket.ts
export class SurbtcMarket {
public ticker: SurbtcMarketView[];
}
export class SurbtcMarketView {
public last_price : number;
public min_ask : number;
public max_bid : number;
public volume : number;
public price_variation_24h : number;
public price_variation_7d : number;
}
组件.ts
import { Http, Response, Headers } from '@angular/http';
import { SurbtcService } from '../../surbtc/surbtc.service';
import {Observable} from "rxjs";
@Component({
selector: 'app-comprarltc',
templateUrl: './comprarltc.component.html',
styleUrls: ['./comprarltc.component.scss']
})
export class ComprarltcComponent implements OnInit {
private prices = [];
constructor(private surbtcService: SurbtcService) {
this.surbtcService = surbtcService;
}
ngOnInit(){
this.surbtcService.getPricess()
.subscribe(
data => this.prices = data.ticker
);
}
}
【问题讨论】:
-
您从
https://www.surbtc.com/api/v2/markets/btc-clp/ticker获得的响应不是 JSON 数组,而是 JSON 对象(在您的情况下是SurbtcMarket的 1 个实例)。你不能在一个对象上使用*ngFor,因为你不能循环它。 -
@NicoVanBelle 感谢您的回复。有没有办法将该对象转换为数组?
-
另外,您将
ticker映射为SurbtcMarketView类型的数组,但同样,它不是数组,而是对象。 -
是的,您可以将 1 对象包装在一个数组中,但您不应该这样做。只需更正您的映射(检查对象/数组的 JSON 规范)并删除使用 *ngFor 循环。
标签: angular http service bitcoin