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

标签 javascript angularjs

<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/

相关文章:

javascript - 如何转到 Angularjs 表达式中数组的下一项?

javascript - 使用 $timeout() 在特定时间间隔后隐藏页脚和页脚消息

javascript - 在输入类型复选框上使用 $scope 函数,并使用 ng Click 或 ngChecked 显示结果

javascript - 如何从 BASH 中的 Node 脚本访问返回值?

java - 如何从 javascript 调用 java 方法

angularjs - AngularJS中模块之间的通信

javascript - 根据输入验证启用/禁用按钮

javascript - 如何创建返回特定字符串的函数

javascript - 使用php从mysql中选择数据,显示在html下拉列表中,并通过javascript插入所选值作为URL参数

javascript - 同一页面上的多个 iScroll 元素