0

I'm doing a simple exchange rate buttons for a website and I'm testing it with a set value under a variable. I'm still getting errors though due to the fact that when I check this variable it shows as undefined. What may be the cause? I know it's basic stuff but I don't see what could be the issue here. Thanks for helping solve this!

Component.ts:

public price: number = 500;
public exchangeUsd;
public priceUsd;

countUsd() {
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then(function(data) {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(this.price) //here the typeof shows undefined
      priceUsd = exchangeUsd * this.price //and it also makes this simple multiplication impossible
    })
}

Stackblitz: https://stackblitz.com/edit/flight-date-picker-with-service-done

JoseTurron
  • 233
  • 2
  • 4
  • 20

3 Answers3

1

Could not test it but it is mostly because of .then(function(data). Replace this with arrow function

.then((data) => {
let exchangeUsd = data.rates[0].mid
}
brk
  • 48,835
  • 10
  • 56
  • 78
1

This is a scope problem. You have two options. Or you use an arrow function in then(...) or you carry the scope to the function by capturing it with a variable:

Option 1: Arrow function

function countUsd() {
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then((data) => {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(price) //here the typeof shows undefined
      priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
    })
}

Option 2: capture the scope with a variable

function countUsd() {
  const classScope = this;
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then(function(data) {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(classScope.price) //here the typeof shows undefined
      priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
    })
}
julianobrasil
  • 8,954
  • 2
  • 33
  • 55
0

You've this.price in the console.log which should be price instead.

The code below will work for you:

public price: number = 500;
public exchangeUsd;
public priceUsd;

function countUsd() {
  fetch("https://api.nbp.pl/api/exchangerates/rates/a/usd/?format=json")
    .then((resp) => resp.json())
    .then(function(data) {
      let exchangeUsd = data.rates[0].mid
      console.log("Exchange rate: " + exchangeUsd)
      console.log(price) //here the typeof shows undefined
      priceUsd = exchangeUsd * price //and it also makes this simple multiplication impossible
    })
}
Sumit
  • 161
  • 5