我只是想使用 web3 api 返回以太坊帐户的余额值,我想在 $scope 中获取该值,以便我可以在我的 html 中使用它。不幸的是,我总是得到一个未定义的值。我怀疑这是因为 web3 可能是异步的,但我不确定。这是我的代码:
app.controller('mainController', function ($scope) {
$scope.showBalance = function(){
web3.eth.getBalance("0xCc26fda641929192B2Fe96BBc37DB5B451Cb9A8c",
function(err, res){
$scope.balance = res.c[0]
console.log("This is inside:" + $scope.balance);
});
console.log("This is outside:" + $scope.balance);
};
angular.element(document).ready(function () {
$scope.showBalance();
});
});
基本上 console.log("This is inside") 有效,我确实得到了正确的值。 但是 console.log("This is outside") 没有,我得到了一个未定义的值。
最佳答案
Unfortunatly i always get a value is undefined. I suspect it is comming from the fact that web3 might be asynchronous but I am not sure.
你猜对了。
这里:
web3.eth.getBalance("0xCc26fda641929192B2Fe96BBc37DB5B451Cb9A8c",
function(err, res){
$scope.balance = res.c[0]
console.log("This is inside:" + $scope.balance);
});
console.log("This is outside:" + $scope.balance);
函数(err,res) 是当getBalance()
函数完成其任务时执行的回调函数。
回调函数声明不是阻塞的。它仅在被调用函数完成其任务时执行,因此返回一个允许调用回调函数以通知其调用者任务结果的 promise 。
所以当 getBlance()
函数被调用时,下一个执行的代码是:
console.log("This is outside:" + $scope.balance);.
但是此时回调函数还没有被调用。
只有当回调函数被调用时
$scope.balance = res.c[0]
被执行。
结论:
你应该删除 console.log("This is outside:"+ $scope.balance);
。
关于javascript - 未定义值 : angularjs $scope and web3. eth.getBalance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42032513/