javascriptangulartypescriptobservablesubscriber

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?


Solution

  • 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)