Search code examples
angularjsangular-resource

"Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array


I try to find a contact, with a specified contactPersonId.

The state to find a contact, that works is:

.state("contactDetail", {
    url: "/contacts/:id",
    templateUrl: "app/contacts/contactDetailView.html",
    controller: "ContactDetailController as viewModel",
    resolve: {
        contactResource: "contactResource",
        contact: function(contactResource, $stateParams){
            var id = $stateParams.id;
            return contactResource.get({id: id}).$promise;
        }
    }
})

Now, when I try to make a more advanced search for the contact with a contactperson in it that has a certain Id, I try to use this:

.state("contactPersonDetail", {
    url: "/contactPerson/:id",
    templateUrl: "app/contacts/contactPersonDetailView.html",
    controller: "ContactPersonDetailController as viewModel",
    resolve: {
        contactResource: "contactResource",
        contactPersoon: function(contactResource, $stateParams){
            var id = $stateParams.id;
            var contacts = contactResource.get();
            var contact;
            for(var i = 0; i < contacts.length; i++){
                if(contacts[i].contactPerson.id == id){
                    contact = contacts[i].contactPerson;
                    break;
                }
            }
            return contact.$promise;

        }
    }
})

When I click on a contactPerson, to view the details of it, I get this error:

"Error: [$resource:badcfg] Error in resource configuration for action get. Expected response to contain an object but got an array (Request: GET http://--url--/api/contacts/)

My questions are: Is it even possible how I try to do it? If yes, what's wrong? If no, how should it?


Solution

  • In the documentation for $resource, see this line under actions:

    isArray – {boolean=} – If true then the returned object for this action is an array, see returns section.

    Basically, you need to specify if your backend is going to return an object or an array, so that it knows how to deal with the data.


    Update: Upon re-reading your comment, it looks like you you are misunderstanding what get() is doing when providing an id vs not providing an id.

    Without seeing your urls, I assume you are calling your backend with something like:

    http://--url--/api/contacts/
    

    &

    http://--url--/api/contacts/<contact_id>
    

    It is likely that the first url returns an array of all contacts (hence your ability to loop over the results). Where as the second url will just return a single contact object.

    This is why for one of the calls, you will need to specify isArray: true.