Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS with ngResource: How to check exact response from server?

Tags:

angularjs

I have created an angular service to talk back to a simple REST server made in PHP. I can see that I am able to get a single record, list of all records, and add new records, however, after adding new records I am having an issue with getting the correct response from the server to be able to act upon it.

I know it's working because the new records are getting added, however, I wish to put notifications for users if for whatever reason the request does not work, and so forth...

This is the service:

angular.module('adminApp.services', ['ngResource'])

    .factory('Settings', function($resource) {

        return $resource('rest/setting/:id', {id: '@id'}, {
            'query' : { method: 'GET', params: {}, format: 'json', isArray: true },
            'save'  : { method: 'POST', params: {}, format: 'json', isArray: true },
            'get'   : { method: 'GET', params: {}, format: 'json', isArray: false },
            'update': { method: 'PUT', params: {id: '@id'}, format: 'json', isArray: true },
            'delete': { method: 'DELETE', params: {id: '@id'}, format: 'json', isArray: false }
    });

});

As part of the controller, I have the following:

$scope.save = function() {
    var result = Settings.save({}, $scope.settings);

    console.log(result);

    // Here I would like to send the result to the dialog
    // to determine wether or not the request was successful
    // dialog.close(result);
};

The Network response from the HTTP request, as seen via the javascript console returns 'true' which comes back from the server, however, the console.log(result) returns an array of the characters in 'true' -- I had guessed this is because of the isArray : true option in 'save' which is necessary because the params get sent to the server as an array though:

[$promise: Object, $resolved: false]
    0: "t",
    1: "r",
    2: "u",
    3: "e",
    $promise: Object,

    // I tried passing result.$resolved to the dialog,
    // but if yousee above it resolves to false up top first
    $resolved: true,
    length: 4,
    __proto__: Array[0]

I know the HTTP response is a json value of true, if I could hook into that it would be easy (I come from a jQuery background, maybe I'm doing it wrong, I have made it a point to remove jQuery completely from this project as to not allow it to inhibit my learning).

I guess the question is, how do I actually get that response from the server onto a JS variable I can actually work with?

Edit: Updated

I changed my service to:

angular.module('adminApp.services', ['ngResource'])
    .factory('Settings', function($http, $resource, $log) {
        return $resource('rest/setting/:id', {id: '@id'}, {
            save   : {
            method: 'POST',
            params: {},
            format: 'json',
            isArray: true,
            transformResponse: [function(data, headersGetter) {
                $log.info(data); // returns true
                return { response: data };
            }].concat($http.defaults.transformResponse)
        },
        update : { method: 'PUT', params: {id: '@id'}, format: 'json', isArray: true },
        delete : { method: 'DELETE', params: {id: '@id'}, format: 'json', isArray: false }
    });

});

And the call to:

$scope.save = function() {
    $scope.results = Settings.save({}, $scope.settings);
    console.log($scope.results); // Still returns the response with $promise
    //dialog.close(true);
};

But I'm still not getting true as the response

like image 966
francisco.preller Avatar asked Jul 02 '13 04:07

francisco.preller


1 Answers

See this fiddle: http://jsfiddle.net/moderndegree/Kn3Tc/

angular.module('myApp', ['ngResource']).
factory('myService', function($http, $resource, $log){
    return $resource('/', {}, {
        get: {
            method: 'GET',
            transformRequest: [function(data, headersGetter){
                // you can examine the raw request in here
                $log.info(data);
                $log.info(headersGetter());
            }].concat($http.defaults.transformRequest),
            transformResponse: [function (data, headersGetter) {
                // you can examine the raw response in here
                $log.info(data);
                $log.info(headersGetter());
                return {tada:"Check your console"};
            }].concat($http.defaults.transformResponse)
        }
    });
}).
controller('myController', function(myService, $scope, $resource, $http, $log) {
    $scope.results = myService.get();
});

To globally augment or override the default transforms, modify the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties.

read more here: http://docs.angularjs.org/api/ng.$http

like image 101
Brian Lewis Avatar answered Sep 30 '22 01:09

Brian Lewis