gpt4 book ai didi

javascript - Angular : variable which is returned by a function in controller is "undefined"

转载 作者:行者123 更新时间:2023-11-30 12:02:00 24 4
gpt4 key购买 nike

<script type="text/javascript">
angular.module('angularApp', ['dialogs.main'])
.controller('TableController', function(dialogs, $http){

function getEmailAddress(){
var emailAddress ="empty";
$http({
//The http method is defined here, which works as expected
}).then(function succes(response) {
emailAddress = response.data;
console.log(emailAddress + " : getEmailAddress success");//From this log, I can see what I expected
return emailAddress; //However, this doesn't return the value, which can be seen in the log.
// return {
// emailAddress:emailAddress
// }; //This way doesn't work either
}, function resendError() {
return "Error!";
});
};

this.resendConfirmationMail = function(orderId){
//Inside this function, the function above is going to be used.
};
});
</script>

我正在尝试做的是创建/使用一个返回值的函数,该值来自 http 函数。

正如我上面描述的,有两个函数,其中一个应该返回一个变量,叫做emailAddress,但是返回的变量被描述为undefined,而不是甚至 empty,作为它的初始值。

我可以从 console.log 中看到正确的返回值,但我不能只返回它。

如有任何建议,我将不胜感激。

最佳答案

getEmailAddress 是一个异步函数(因为它使用 $http 也是异步的)。您可以从 getEmailAddress 方法返回 promise 并使用 then 获取电子邮件地址:

function getEmailAddress() {
return $http({
//The http method is defined here, which works as expected
});
}

this.resendConfirmationMail = function (orderId) {
getEmailAddress().then(function (emailAddress) {
console.log(emailAddress);
});
};

复习一下异步编程和 Promises 可能会有所帮助

Here是一个很好的总结使用异步函数的答案。

关于javascript - Angular : variable which is returned by a function in controller is "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36420968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com