我可以从简单的json获取数据,但是我尝试从更复杂的(对我来说)json获取数据,并且我可以获得初始数据,但是我在获取其余数据方面遇到了麻烦。我的json(link):
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;
}
你不能像你一样从问中得到价值。因为ask在rates数组中。你可以做<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>
当你订阅你收到
[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