Search code examples
javascriptjsonangularjsangular-resourcedhtmlx-scheduler

Extract JSON object from $resource.get promise


I have just started exploring AngularJS. Is there any way by which I can extract the original JSON returned from server?

I am trying to get some data using $resource.get from a WebAPI. The returned promise contains some additional properties compared to my original JSON.

When I assign this object (returned from $resource.get) to some of my Javascript controls (like DHTMLX Scheduler), it does not work correctly but if I use $http it returns pure JSON and the control works perfectly.

I am more interested in using $resource as it has been used in the rest of the Angular controllers.


Solution

  • Let's say you have a service that's defined using a resource:

    app.factory('LoginService', function($resource, API_URL) {
        return $resource(API_URL + '/login.json');
    });
    

    Then elsewhere in a controller (for example) you want to use that service:

    var loginRequest = LoginService.get({
        email: email,
        password: password
    }).$promise;
    
    loginRequest.then(function onSuccess(response) {
        // access data from 'response'
        var foo = response.foo;
    },
    function onFail(response) {
        // handle failure
    });
    

    The key is that you need to access $resource.get().$promise, not $resource.get().