Robert
Robert

Reputation: 4406

Why is angular calling the server out of order?

I have a controller method that I call service methods in. Angular is calling the Server out of order:

controller:

$scope.add = function () {
        var waiver = new MyObject();
        service.add(waiver);
        service.getLast().then(function (result) {
            $scope.model.myObjects.push(result.data);
        });
    }

Service:

this.add = function (waiver) {
        $http({
            method: "POST",
            url: "api/theServer/Add/",
            data: waiver
        });
    };



    this.getLast = function() {
        return $http({
            method: "GET",
            url: "api/TheServer/GetLast"
        })
        .success(function (data) {
            return data;
        })
        .error(function (data) {
            console.log(data);
            alert("EPIC FAIL");
        })
        ;
    };

If I use Chromes debugging tools, angular calls the SERVICE methods in the right order; however, when the actual Server is called GetLast is called before Add. I need these to be called in order on the server.

Any Suggestions?

Upvotes: 0

Views: 442

Answers (1)

Josh
Josh

Reputation: 44906

You are calling these asyncronously so there is no guarantee of ordering. If you need to guarantee that one call happens before the other, then you need to chain the calls:

service.add(waiver)
   .then(function(){
       return service.getLast();
    })
   .then(function (result) {
       $scope.model.myObjects.push(result.data);
   });

Upvotes: 2

Related Questions