Bye
Bye

Reputation: 2806

AngularJS - Web API - HttpResponseMessage - Pass Custom Error

Very simple form with only one input - "Name". However, I do not want duplicates in the table.

On the server side I can check this, and pass a custom message to the response header "Name already Exists".

How do I go about getting the save() method in my angular controller to see this message and pass an alert('Name already exists') ?

Thanks all.

What is to show??

You open the form in Chrome, select developer tools, then network. Put a name you already know is in the database, click Submit, then click on the API, then the response tab where my server passed the message "Name already exists".

I just need to know how to get Angular in the save method to pick up that message. Angular knows the data wasn't saved; it stays on the form, but the user has no clue why he/she hasn't moved off the form after submit. I need them to see that the name is already in the db.

grendian

Thanks for your response, I think you are on to something. I will try that tomorrow and get back to you.

Upvotes: 1

Views: 1570

Answers (2)

Bye
Bye

Reputation: 2806

I was not able to find a solution via my API resources so I decided to use $http which the below does indeed work:

$scope.save = function () {

$http.post('/api/TruckMfgs/', $scope.truckMfg)  
    .success(function () {
    })
    .error(function (data) {
        alert(data);
    });

}

Upvotes: 0

grendian
grendian

Reputation: 4158

You can use callbacks on resource methods for success and fail.

resource.save(function(data){
    console.log('saved with response:', data);
}, function(err){
    console.log('failed with response:', data);
});

Upvotes: 1

Related Questions