Norbert Norbertson Norbert Norbertson - 22 minutes ago 2
AngularJS Question

Why is AngularJS json data nested?

I have a service returning this simple json:

{
"successYN": true,
"msg": "Success!",
"errors": null
}


I have this controller:

app.controller('formController', function ($http, $httpParamSerializerJQLike) {
var frmVM = this
frmVM.formData = {}

frmVM.frmSubmit = function () {
console.log('form was submitted with: ' + frmVM.formData.name + ' ' + frmVM.formData.superheroAlias)

// post the data to the back end
$http({
method: 'POST',
url: '/contact-post',
data: $httpParamSerializerJQLike(frmVM.formData), // pass in data as strings
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.then(function (data) {

console.log(data);

var innerData = data.data;

console.log(innerData)
console.log(innerData.errors)
console.log(innerData.successYN)

if (!innerData.successYN) {
console.log("Not successful!")
// if not successful, bind errors to error variables
frmVM.errorName = innerData.errors.name;
frmVM.errorSuperhero = innerData.errors.superheroAlias;
} else {
// if successful, bind success message to message
frmVM.message = innerData.msg;
}
});
};
})


I am
controller as
syntax in my form and everything works fine. However, the
data object I am seeing in looks like this:

enter image description here

Therefore, the data has to be accessed like this:

var innerData = data.data;


Before I can access the data:

console.log(innerData.successYN)


Can anyone explain why this is happening and/or what I am doing wrong?

Answer

In argument "data" is basically response object which contains response headers as well as body of the response. ForExample: If you need the argument response then to get response data you will have to call

var data = response.data

and If you want to get header from response you will have to do following:

var authorization = response.headers('Authorization');

In .then function you will have to pass 2 handlers 1 for success response(200 OK) and 2nd for failure response(400 Bad Request)

So

.then(function(response) {
// here you extract data from response. like response.data
}, function(errorResponse) {
// handle error here like errorResponse.status
});