Angular 9:从HTTP get中读取JSON
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Angular 9:从HTTP get中读取JSON相关的知识,希望对你有一定的参考价值。
我只需要提取某些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']);
});
});
我在做什么错?
答案
您可以检查此链接angular9-example
另一答案
示例此测试数据中的数组应按预期工作
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']);
});
示例链接here
以上是关于Angular 9:从HTTP get中读取JSON的主要内容,如果未能解决你的问题,请参考以下文章
在 Angular 服务中 HTTP.get 之后从 firebase 返回的重复数组
使用Angular 7获取“无法读取未定义的属性'http'”
使用 AngularJS 读取 GeoJSON 页面 [重复]