3

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?

2 Answers 2

9

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"
});
4
  • 1
    could you provide more code? I always get nil/null for account variable May 21, 2018 at 13:44
  • @VyachaslavGerchicov the code I posted is from OP. Are you running a ganache or testrpc? You need a node with accounts.
    – martriay
    May 21, 2018 at 14:47
  • @martriay ganache works - it shows a list of wallets I can use. So that way works. But what to do with metamask? It shows one account address too but the code above doesn't have an access to it May 21, 2018 at 14:49
  • I am not able to install web3 in angular 5 Oct 16, 2018 at 13:40
1

web3.eth.getBalance(this.userWalletAddress, (err, balance) => { this.userBalance = web3.utils.fromWei(balance, "ether") + " ETH" });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.