我试图在dom中显示一些信息,但是我收到了这个错误:
错误:尝试区分[对象对象]'
时出错
我尝试做的是从https://www.surbtc.com/api/v2/markets/btc-clp/ticker迭代这些数据:
{"股票" {" last_price":[" 1771455.0"" CLP&#34]," min_ask&# 34;:[" 1771432.0"" CLP&#34]," MAX_BID":[" 1660003.0"" CLP&# 34],"体积":[" 178.37375119"" BTC&#34]," price_variation_24h":" -0.107& #34;" 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;
}
component.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
);
}
}
答案 0 :(得分:3)
如果您希望将price
作为数组,则push
数组中的对象为prices
。
ngOnInit(){
this.surbtcService.getPricess()
.subscribe(
data => this.prices.push(data.ticker);
);
}
或者,您可以通过将data.ticker
分配给prices
来直接访问对象属性。
private prices = new SurbtcMarketView();
constructor(private surbtcService: SurbtcService) {
}
ngOnInit(){
this.surbtcService.getPricess()
.subscribe(data =>{
this.prices = data.ticker;
});
}
HTML:
<div *ngFor="let item of prices.min_ask">
{{item}}
</div>
更新:
请参阅Plnkr demo,我已经解决了在解析json响应时导致错误的问题。
答案 1 :(得分:0)
否则,您也可以使用它,
prices : SurbtcService[] = [];
然后您可以推送用户对象并将其制成数组,
this.prices.push(<<the data you want to push>>);
答案 2 :(得分:-1)
public getPricess() :Observable<SurbtcMarket> { return this.http.get('https://www.surbtc.com/api/v2/markets/btc-clp/ticker') .map((response: Response) => response.json() as SurbtcMarket); }
这可能是因为它没有映射到一个类型。我假设这只会返回一个对象,否则你必须返回一个数组。
public getPricess() :Observable<SurbtcMarket[]> { return this.http.get('https://www.surbtc.com/api/v2/markets/btc-clp/ticker') .map((response: Response) => response.json() as SurbtcMarket[]); }