Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - Angular $resource does not parse correctly an integer response

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...