Angular 9: чтение JSON из HTTP get - PullRequest
0 голосов
/ 25 апреля 2020

Мне нужно извлечь только одно значение из JSON данных, предоставляемых мне некоторыми API. Дело в том, что я не могу получить доступ к контенту внутри «Курса обмена валют в реальном времени». Ниже приведен мой код и то, что я пытаюсь выполнить. Заранее большое спасибо!

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']);
          });
        });

Что я делаю не так?

Ответы [ 2 ]

1 голос
/ 26 апреля 2020

Вы можете проверить эту ссылку angular9-example

 apiService
  .getExchangeRate("hello", "world")
  .pipe(
    map(x => x["Realtime Currency Exchange Rate"]),
    pluck("5. Exchange Rate")
  )
  .subscribe((v: PairDetails) => {
    console.log(v);        
  });
0 голосов
/ 25 апреля 2020

пример, этот массив в тестовых данных должен работать как положено

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']);
});

пример ссылки здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...