如何使用angularjs获取变量中的函数返回值

时间:2018-09-24 07:52:14

标签: 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";
        });

1 个答案:

答案 0 :(得分:0)

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

click here for more detail

使用了此功能

$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;
};