Angular $resource does not parse correctly an integer response
Asked Answered
P

4

7

I am using the Angular $resource to make requests to my controllers, implemented on a Spring application. When the controller returns just an Integer value, $resource parse it bad. Inspecting it with Firebug I get something like:

Resource { 0="1", 1="9", 2="1", more...}

where 191 is just the intger value the server returns. No trouble with others complex object (parsed in JSON by the server). Suggestions? Thanks FB

Patrilocal answered 27/3, 2014 at 18:40 Comment(0)
B
4

I know this is a little old, but I just ran into a similar problem and someone pointed me in the right direction.

If your server is sending back a JSON encoded resonse, but you only pass it a single value (191 in your case), $resource seems to interpret it as a string, which it is then splitting into an array of individual characters (I'm not 100% on the technical details of why, but that was my experience). So what you need to do is send back your value wrapped inside of a JSON object.

So, instead of doing something like:

function callback(req, res) {
    var number = 191;  // this is just for example purposes
    res.json(number);
}

You need to do something like:

function callback(req, res) {
    var number = 191;  // again, just for an example
    res.json({ value: number });
}

Then when your $resource call comes back, just access the value property of the response and you should be good to go.

P.S. The examples here are based on a Node/Express back end, not Spring, but I think this should still apply.

Bruner answered 16/6, 2014 at 19:9 Comment(1)
This actually solved my issue, I was providing res.json with a string of a JSON object instead of a JSON Object.Butterfly
H
0

Set isArray: false in the $resource method definition.

Harts answered 27/3, 2014 at 18:51 Comment(0)
C
0

Maybe try setting the responseType in the action config, like this:

$resource(url, {}, {
    get: {
        method: 'GET',
        responseType: 'text'
    }
});

If that doesn't work you probably need to use transformResponse or an $http interceptor to modify the response before the resource gets a hold of it. See $http docs.

Cierracig answered 27/3, 2014 at 19:25 Comment(0)
S
0

I've actually found this to be an issue with integers, strings, and bools.

If you are using WebAPI, do something like this:

public object ControllerMethod(<PARAMS>)
{
    <LOGIC>
    return new { value = <PUT YOUR VALUE HERE> };
}

If Node, use CodeLander's answer.

In your Angular code, you'll just have to get the .value of what's returned.

Stonybroke answered 6/1, 2016 at 19:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.