首页 > 解决方案 > 如何使用angularjs在变量中获取函数返回值

问题描述

这是我的 angularjs 文件代码

$scope.httpPost = function (url, json_form_data) {

    $http.post(url, json_form_data)
            .then(function (response) {

                $scope.responseData = response.data;
                return $scope.responseData;
            }, function (response) {
                $scope.content = "Something went wrong";
            });
};

这是我调用上述函数的函数

$scope.getAuthToken = function (account_type, auth_type, email, type_of_request) {  // type of request means login or signUp


    var account_type = account_type;

    var form_data = {
        'email': email,
        "auth_type": auth_type,
        "account_type": account_type
    };

    $scope.responseData = $scope.httpPost($scope.authTokenUrl, form_data);
    console.log("value of res");
    console.log($scope.responseData);
};

上面代码的输出是

value of res
loginAndSignup.js:138 undefined

我的问题是我如何访问函数返回的值,因为我需要那个值。

我尝试了以下解决方案

$scope.httpPost = function (url, json_form_data) {

return $http.post(url, json_form_data)
        .then(function (response) {

            return  response;

        }, function (response) {
            $scope.content = "Something went wrong";
        });
};



$scope.login = function (email, auth_token, auth_type, account_type) {

var password = $scope.password;

var form_data = {
    //form data
};

var url = $scope.loginUrl;
$scope.httpPost(url, form_data)
        .then(function (response) {

            return  response;

        }, function (response) {
            $scope.content = "Something went wrong";
        });

标签: angularjs

解决方案


using $q(帮助您异步运行函数的服务,并在完成处理时使用它们的返回值(或异常)。)

点击这里了解更多详情

使用了这个功能

$scope.httpPost = function (url, json_form_data) {
    var d = $q.defer();
    $http.post(url, json_form_data)
            .then(function (response) {
                   d.resolve(response);
             }, function (response) {
               d.reject(response);
            });

   return d.promise;
};

推荐阅读