未定义的值:angularjs $scope 和 web3.eth.getBalance
Undefined value: angularjs $scope and web3.eth.getBalance
我只是想 return 使用 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()
函数完成任务时执行的回调函数。
回调函数声明不是阻塞的。它仅在被调用函数完成其任务时执行,因此 return 允许调用回调函数以通知其调用者任务结果的承诺。
所以当getBlance()
函数被调用时,接下来执行的代码是:
console.log("This is outside:" + $scope.balance);.
但是此时回调函数还没有被调用
只有当回调函数被调用时
$scope.balance = res.c[0]
被执行。
结论:
你应该删除 console.log("This is outside:" + $scope.balance);
.
我只是想 return 使用 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()
函数完成任务时执行的回调函数。
回调函数声明不是阻塞的。它仅在被调用函数完成其任务时执行,因此 return 允许调用回调函数以通知其调用者任务结果的承诺。
所以当getBlance()
函数被调用时,接下来执行的代码是:
console.log("This is outside:" + $scope.balance);.
但是此时回调函数还没有被调用
只有当回调函数被调用时
$scope.balance = res.c[0]
被执行。
结论:
你应该删除 console.log("This is outside:" + $scope.balance);
.