Nikos4Life Nikos4Life - 4 months ago 16
Javascript Question

AngularJS - Stuck Handling response after $resource.save (expecting json)

Hello first of all thanks for your support,

I getting started with angular and I am trying to use conmsume data from an API for my app. I am having a few problems with this.
First of all CORS:

To run local http server I am using the one that comes with node.js (using http-server command).
I am using http://www.mocky.io/ to test the app. I've generated differents (with headers I've found around the net that are supposed to fix it) response there to try to fix CORS (always getting preflight error) but nothing seems to work.
I have added this to my save method (inside a factory):

save: {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*'
}
}


If I use a Chrome extension called CORS I can bypass that and receive response but then I am not able to manage the promise and get the data inside the response. I would like to be able to show the response's json on the view.

$scope.submitForm = function() {
var promise = null;
promise = CheckFactory.save($scope.partner).$promise;
$scope.result = promise.data;
}


This functions sends the data from the form to the factory and perform the request but then I am lost and do not know how to manage the data I need from the response.

Thanks in advance :)

Answer

Basically you need to put .then function over your save method call promise. So that will call .then function's once data save request gets completed.

$scope.submitForm = function() {
    CheckFactory.save($scope.partner).$promise
    //it will called success callback when save promise resolved.
    .then(function(data){ //success
       $scope.result = data;
    }, function(error){ //error
    });
}