T. Ferreira T. Ferreira - 3 months ago 9
AngularJS Question

How to save the database ID when using $http.post?

I'm using AngularJS and I want to make two POSTs, on which the second POST needs the database ID of the first POST.

For example:

Let's say the first POST is an entity with two parameters: "ID" and "Name". I send the "Name" and the ID is generated automatically in the database. This is the code:

var save;

$scope.entityA =
{
'Name': 'Some name'
};

$http.post(url, JSON.stringify($scope.entityA)).then(function (response) {
save = response.data;
console.log(save.Id); // this logs the correct ID;
}
);


Then I have a second POST in which one of the parameters is the ID of the first POST. Like this:

$scope.entityB =
{
'Title': 'Whatever',
'EntityA_Id': save.Id; // this doesn't work because it says "save" is undefined
};

$http.post(url, JSON.stringify($scope.execution)).then(function (response) {
console.log(response.data);
}
);


However, this doesn't work. How can I do a POST of the first entity and then use its database ID for the second POST?

Thanks.

Answer

I suspect you might be calling the second post before the first post returned the ID. Try this:

$http.post(url, JSON.stringify($scope.entityA)).then(function (response) {
        save = response.data;
        callSecondPostMethod(); 
    }