Search code examples
javascriptangularfetchundefinedtypeof

Variable with assigned value is still undefined when checked with typeof


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


Solution

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