Angular 9: Read JSON from HTTP get



我只需要提取一些API提供给我的JSON数据的一个值。问题是我无法访问"实时货币汇率"中的内容。下面是我的代码以及我正在努力实现的目标。提前,非常感谢!

JSON数据

{
"Realtime Currency Exchange Rate": {
"1. From_Currency Code": "USD",
"2. From_Currency Name": "United States Dollar",
"3. To_Currency Code": "NOK",
"4. To_Currency Name": "Norwegian Krone",
"5. Exchange Rate": "10.60921000", //Need to obtain just this one
"6. Last Refreshed": "2020-04-25 18:34:28",
"7. Time Zone": "UTC",
"8. Bid Price": "10.60921000",
"9. Ask Price": "10.61031000"
}

}

接口

export interface PairDetails {
'Realtime Currency Exchange Rate': PairDetailed[];
}
export interface PairDetailed {
'1. From_Currency Code': string;
'2. From_Currency Name': string;
'3. To_Currency Code': string;
'4. To_Currency Name': string;
'5. Exchange Rate': string;
'6. Last Refreshed': string;
'7. Time Zone': string;
'8. Bid Price': string;
'9. Ask Price': string;
}

获取值的代码

private getExchangeRate(pair1: string, pair2: string) {
return this.http.get(`https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=${pair1}&to_currency=${pair2}&apikey=demo`);
}
this.getExchangeRate(separarDivisas[0], separarDivisas[1]).subscribe((v: PairDetails) => {
const val = v['Realtime Currency Exchange Rate'];
Object.values(val).forEach((data) => {
console.log(data['5. Exchange Rate']);
});
});

我做错了什么?

你能检查这个链接角度9 示例吗

apiService
.getExchangeRate("hello", "world")
.pipe(
map(x => x["Realtime Currency Exchange Rate"]),
pluck("5. Exchange Rate")
)
.subscribe((v: PairDetails) => {
console.log(v);        
});

示例测试数据中的此数组应按预期工作

export interface PairDetails {
'Realtime Currency Exchange Rate': PairDetailed[];
}
export interface PairDetailed {
'1. From_Currency Code': string;
'2. From_Currency Name': string;
'3. To_Currency Code': string;
'4. To_Currency Name': string;
'5. Exchange Rate': string;
'6. Last Refreshed': string;
'7. Time Zone': string;
'8. Bid Price': string;
'9. Ask Price': string;
}
let test = {
"Realtime Currency Exchange Rate": [{
"1. From_Currency Code": "USD",
"2. From_Currency Name": "United States Dollar",
"3. To_Currency Code": "NOK",
"4. To_Currency Name": "Norwegian Krone",
"5. Exchange Rate": "10.60921000", //Need to obtain just this one
"6. Last Refreshed": "2020-04-25 18:34:28",
"7. Time Zone": "UTC",
"8. Bid Price": "10.60921000",
"9. Ask Price": "10.61031000"
}]
} as PairDetails;
let key: keyof PairDetails = 'Realtime Currency Exchange Rate';
const values = test[key];
console.log(values);
Object.values(values).forEach((data) => {
console.log(data['5. Exchange Rate']);
});

此处的示例链接

最新更新