Dark Cyber Dark Cyber - 14 days ago 5
AngularJS Question

AngularJS variable from first response not passed to second request?

I am using Parse.com as backend, I need to send post twice, first for

_User
class and
customer
class.
Customer
class have
user_id
field which pointer to
_User.objectId
.

The scenario is I send post to
_User
get the objectId, and send post to
customer
which contain
_User
objectId.

Here is my code

$http.post('http://128.199.249.xxx:1337/parse/users', data, configRegister).then(function (response) {
console.log(response);
$scope.userObjectId = response.data.objectId;
console.log($scope.userObjectId); //succes print objectId
}, function (error) {
alert(error.data.error);
});


var dataProfileCustomer = {
user_id : {
__type: "Pointer",
className: "_User",
objectId: $scope.userObjectId //this part is not exist when I check in post request
},
family_name: $scope.customer.family_name,
family_phone: $scope.customer.family_phone,
family_address: $scope.customer.family_address
};

$http.post('http://128.199.249.xxx:1337/parse/classes/customer', dataProfileCustomer, configRegister).then(function (response) {
console.log(response.data);
}, function (error) {
alert(error.data.error);
});


The above code result successfully insert in 2 class,
customer.user_id
is undefined.

Is something missing or wrong with my code?

Answer

You have to write second http.post request code inside the success response of first http.post request.

$http.post('http://128.199.249.xxx:1337/parse/users', data, configRegister).then(
function (response) {
    console.log(response);  
    $scope.userObjectId = response.data.objectId;
    console.log($scope.userObjectId); //succes print objectId

    var dataProfileCustomer = {
        user_id : {
            __type: "Pointer",
            className: "_User",
            objectId: $scope.userObjectId //this part is not exist when I check in post request
        },
        family_name: $scope.customer.family_name,
        family_phone: $scope.customer.family_phone,
        family_address: $scope.customer.family_address
    };
    $http.post('http://128.199.249.xxx:1337/parse/classes/customer', dataProfileCustomer, configRegister).then(
    function (response) {
        console.log(response.data); 
    }, function (error) {
        alert(error.data.error);
    });


}, function (error) {
    alert(error.data.error);
});
Comments