rel1x
rel1x

Reputation: 2441

Can't get response from Angular $resource

I have a factory:

.factory('CompanyRolesResource', function($resource, FdConfig) {
    return $resource(FdConfig.routes.companyRoles);
})

And I have a function that use this factory:

ctrl.saveCompanyRole = function(companyRole) {
    return CompanyRolesResource.save({}, companyRole).$promise.then(function (response) {
            console.log(response)
        });
    };

In Chrome DevTools I see that response is data like {status: 200, data: {...}}. But in console.log I just see:

Resource
$promise: Promise
$$state: Object
__proto__: Object
$resolved: true

Where is my data? I can't find it also inside of $promise and $$state.

UPD:

I get right response when I use this way:

   $http({
        url: FdConfig.routes.companyRoles,
        method: "POST",
        data: companyRole
    }).then(function (response) {
        console.log(response.data);
    });

But my console.log(response) in factory returns undefined.

Upvotes: 1

Views: 842

Answers (3)

georgeawg
georgeawg

Reputation: 48968

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

Under the hood, the ngResource API uses angular.copy to copy the server data to the empty reference. If the data is not a JavaScript object, nothing will be copied.

In the case of the .save action method, if an array is returned, a $resource:badcfg error will be thrown.

Error: $resource:badcfg

Response does not match configured parameter

Description

This error occurs when the $resource service expects a response that can be deserialized as an array but receives an object, or vice versa. By default, all resource actions expect objects, except query which expects arrays.

To resolve this error, make sure your $resource configuration matches the actual format of the data returned from the server.

For more information, see the $resource API reference documentation.

— AngularJS $resource:badcfg Error Reference

Upvotes: 1

anilCSE
anilCSE

Reputation: 2461

Resource is your data object. When you use $resource, you don't get the response as (status, data, headers, config) Object. You will directly get the response (your expected response data)

Upvotes: 1

Vladyslav
Vladyslav

Reputation: 786

You can't access your data from $resource directly as it is retrieved from server asynchronously. This means that your data isn't yet loaded when you try to access it. What you need to do is to supply callback for $resource action.

Starting from Angular 1.2, $resource provides you $promise for each action which you can use to retrieve your data when it's loaded:

CompanyRolesResource.save({}, companyRole).$promise.then(function (response) {
    // do whatever you want with your response.data here
});

Upvotes: 2

Related Questions