Search code examples
angularjsangular-resourcengresourceangularjs-ng-resource

Get the response using ngResource


I created a factory where I have a method forming the object 'create' and the controller causes through submit REST command. Now I would like a response data because the console I can see that the request was successful. How to do it ? How to get the response? I would add that for me it numeral 32.

app.factory('Claims', ['$resource', function($resource) {
        return $resource('/portal/rest/registerClaim', null,
            {
                'create': { method: 'POST' }
            });
        }]);

app.controller('ClaimCtrl', ['$scope', 'Claims', function($scope, Claims) {

        $scope.registerClaim = function (PIN) {
            console.log(PIN);
            var obj = {
                    "t":t,
                    "a":"t",
                    "b":"z",
                    "c":"x",
                    "d":"q"
            };
            var a= Claims.create(obj);
            console.log(a);

        }
    }]);

Solution

  • methods of ngResource is asynchronous, so you can get response using $promise

    you can read this document about $resource. https://docs.angularjs.org/api/ngResource/service/$resource

    I changed your code in here.

    app.factory('Claims', ['$resource', function($resource) {
        return $resource('/portal/rest/registerClaim', null,
            {
                'create': { method: 'POST' }
            });
        }]);
    
    app.controller('ClaimCtrl', ['$scope', 'Claims', function($scope, Claims) {
    
        $scope.registerClaim = function (PIN) {
            console.log(PIN);
            var obj = {
                    "t":t,
                    "a":"t",
                    "b":"z",
                    "c":"x",
                    "d":"q"
            };
            Claims.create(obj).$promise.then(function(resp) {
              $scope.resp = resp;
            });
    
        }
    }]);