Quentin
Quentin

Reputation: 25

How do I get the value from this API?

  getCoinPrice(coinName: string) {
return this._http
  .get(
    `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coinName}&tsyms=EUR`
  ).pipe(map((result) => (result)));

JSON from the link with "BTC" as coinName is: {"BTC":{"EUR":8226.43}} and the method gives me back an observable.

How would I return the price value(8226.43) in a variable?

Upvotes: 2

Views: 414

Answers (3)

aks44
aks44

Reputation: 432

As per observable result you are getting {"BTC":{"EUR":8226.43}} for coinName BTC, you want to retrieve "8226.43" from it.

So, coinName = 'BTC' & observableResult = {"BTC":{"EUR":8226.43}}

If you want to get the value based on coinName, you could use the below method since coinName is also the key (BTC) in the observableResult object.

observableResult[coinName] // This will result to {EUR: 8226.43}

So, observableResult[coinName].EUR will result to 8226.43

Upvotes: 1

Always Helping
Always Helping

Reputation: 14570

Try this code. Should just work fine for you.

getCoinPrice(coinName: string) {
    return this._http
    .get(
      `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coinName}&tsyms=EUR`
  ).pipe(map((result) => (result.BTC.EUR)));

You can learn more about how to access objects and their value here https://www.w3schools.com/js/js_objects.asp

Here is the Javascript MDN explanation about how to work with objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Working example:

This is to show how we will get the value you desired by accessing the objects with .

//Your results
var result = JSON.parse('{"BTC":{"EUR":8226.43}}');

//This will print out 8226.43
console.log(result.BTC.EUR)

Upvotes: 1

Rahul Bhobe
Rahul Bhobe

Reputation: 4451

You want result[coinName]["EUR"]

Upvotes: 1

Related Questions