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;
    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 = 
declare var window: any;
account: any;
accounts: any;
web3: any;
balance: number;

this.web3.eth.getAccounts((err, accs) => {      
  if (err != null || accs.length === 0) {
  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?


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"
| improve this answer | |
  • could you provide more code? I always get nil/null for account variable – Vyachaslav Gerchicov May 21 '18 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 '18 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 – Vyachaslav Gerchicov May 21 '18 at 14:49
  • I am not able to install web3 in angular 5 – Kunvar Singh Oct 16 '18 at 13:40

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.