简体   繁体   中英

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.

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(); 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM