我可以从简单的json获得数据,但是我尝试从一个更复杂的json (对我来说)获得数据,我可以获得初始数据,但是我在获取其余的数据时遇到了困难。My (链接):
0
table "C"
no "043/C/NBP/2018"
tradingDate "2018-02-28"
effectiveDate "2018-03-01"
rates
0
currency "dolar amerykański"
code "USD"
bid 3.3875
ask 3.4559
1
currency "dolar australijski"
code "AUD"
bid 2.6408
ask 2.6942
2
currency "dolar kanadyjski"
code "CAD"
bid 2.6468
ask 2.7002我可以得到这样的数据,不,tradingDate或effectiveDate,但我不能从利率数据,例如。货币,代码,出价或索要。如何从我的json中获得这些数据?我的服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import "rxjs/Rx";
import {Npb} from './npb';
import { Http , Response, HttpModule} from '@angular/http';
@Injectable()
export class NbpService {
private _postsURL = "http://api.nbp.pl/api/exchangerates/tables/c/?format=json";
constructor(private http: Http) {
}
getPosts(): Observable<Npb[]> {
return this.http
.get(this._postsURL)
.map((response: Response) => {
return <Npb[]>response.json();
})
}
private handleError(error: Response) {
return Observable.throw(error.statusText);
}
}构成部分:
import { Component, OnInit } from '@angular/core';
import {NbpService} from './nbp.service';
import {Npb} from './npb';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
providers: [NbpService]
})
export class HomeComponent implements OnInit {
_postsArray: Npb[];
constructor(private NbpService: NbpService, ) {
}
getPost(): void {
this.NbpService.getPosts()
.subscribe(
resultArray => this._postsArray= resultArray,
error => console.log("Error :: " + error)
)
}
ngOnInit(): void {
this.getPost();
}
}和html:
<tr *ngFor="let post of _postsArray">
<td>USD</td>
<td>{{post.effectiveDate}}</td>
<td>{{post.tradingDate}}</td>
<td>{{post.ask}}</td>
</tr>和Nbp:
export interface Npb {
date: string;
buy: string;
sel: string;
}发布于 2018-03-02 07:56:47
你不能像你那样从询问中得到价值。因为ask在速率数组中。您可以执行<td>{{post.rates[0].currency}}</td>,这将为数组的第一个元素提供货币。
如果要打印所有费率,则必须执行另一个循环:
<tr *ngFor='let rate of post.rates'>
<td>{{rate.currency}}</td>
<td>{{rate.code}}</td>
<td>{{rate.bid}}</td>
<td>{{rate.ask}}</td>
</tr>发布于 2018-03-02 07:50:53
当你订阅你收到
[table:..,rates:[{currency:aa,code:bb,}{{currency:aa,code:bb,}..]那是:一个元素的数组,所以
result[0]={table:..rates:[{...},{...}]}和
result[0].rates={{...},{...}]所以
getPosts(): Observable<Npb[]> {
//See that I use httpClient
return this.httpClient
.get(this._postsURL)
.map((response: any) => { //see that we received response:any
return response[0].rates;
})
}注意:使用httpClient而不是“旧”http,请参阅https://angular.io/guide/http#httpclient
https://stackoverflow.com/questions/49064556
复制相似问题