SaMeEr SaMeEr -4 years ago 103
AngularJS Question

Issue in accessing object property in javascript shows undefined?

I am just calling api which returns josn encoded data and trying to print object property but shows undefined but when I print that object , the object has that property and value.

my code

function sendData(postData, url){
var response = apiCall(postData,url);
console.log(response.email)
console.log(response.count);
}


function apiCall(postData, postUrl){
var response = {};
$http({
method : 'POST',
url : postUrl,
data : postData,
headers : {'Content-Type': 'application/json'}
}).success(function(data) {
console.log(data)
for (var attr in data) {
if (data.hasOwnProperty(attr)) response[attr] = data[attr];
}
});

return response;
}


php based api

<?php
$_POST = json_decode(file_get_contents('php://input'), true);
$response = array();

$response['email'] = $_POST['oauth']['email'];
$response['type'] = $_POST['oauth']['type'];
echo json_encode($response);
?>


response data in console


Object {email: "sameerdighe14@gmail.com", type: "google"}

Answer Source

You need to use promises to make it work. Your success function is called async once the HTTP-Request has finished with success. In that way return response; is executed before the request has been finished -> so it is still an empty object {}. Use AngularJS promises to make it work. This is a simple working fiddle example.

function sendData(postData, url){

    var filteredData = {};

    apiCall(postData,url).then(function (response) {

        for (var attr in response.data) {
            if (response.data.hasOwnProperty(attr)) {
                filteredData[attr] = response.data[attr];
            }
        }

        console.log(filteredData.email);
        console.log(filteredData.count);
    });
}


function apiCall(postData, postUrl){
    return $http({
        method  : 'POST',
        url     : postUrl,
        data    : postData,
        headers : {'Content-Type': 'application/json'}
    });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download