как получить возвращаемое значение функции в переменной, используя angularjs - PullRequest
0 голосов
/ 24 сентября 2018

Вот мой код файла 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 голосов
/ 24 сентября 2018

с использованием $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;
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...