[Ethereum] Getting Metamask account’s balance using fromWei

angular2balancestypescriptweb3js

Using web3 javascript code to get selected account's balance in Metamask and show it in html,

web3.eth.getCoinbase(function(err, account) {
  if (err === null) { 
    App.account = account;
    $("#account").text(account);
    web3.eth.getBalance(account, function(err, balance) {
      if (err === null) {
        $("#accountBalance").text(web3.fromWei(balance, "ether") + " ETH");
      }
    });
  }
});

and now I'm using angular 4 trying to convert above code to typescript.

const Web3 = require('web3');
const contract = require('truffle-contract');
const myBettingArtifact = 
require('../../../build/contracts/Test.json');
declare var window: any;
...
account: any;
accounts: any;
web3: any;
balance: number;

this.web3.eth.getAccounts((err, accs) => {      
  if (err != null || accs.length === 0) {
    return;
  }
  this.accounts = accs;
  this.account = this.accounts[0];

  this.web3.eth.getBalance(this.account, function(err, balance) {
    this.balance = this.web3.fromWei(balance, "ether") + " ETH"        
  });
}); 

However I get an error

Uncaught TypeError: Cannot read property 'fromWei' of undefined

What is the problem here?

Best Answer

Apparently, this is not the same inside the anonymous callback function you're passing to getBalance. Try replacing it with a fat arrow function, that binds the outer this value to the inner scope.

this.web3.eth.getBalance(this.account, (err, balance) => {
  this.balance = this.web3.fromWei(balance, "ether") + " ETH"
});
Related Topic