Angular $resource 无法正确解析整数响应 [英] Angular $resource does not parse correctly an integer response

查看:31
本文介绍了Angular $resource 无法正确解析整数响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular $resource 向我的控制器发出请求,在 Spring 应用程序上实现.当控制器只返回一个 Integer 值时,$resource 将其解析为错误.用 Firebug 检查它,我得到类似的信息:

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...}

其中 191 只是服务器返回的整数值.其他复杂对象没有问题(由服务器解析为 JSON).建议?谢谢脸书

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

推荐答案

我知道这有点老了,但我刚刚遇到了类似的问题,有人为我指出了正确的方向.

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

如果您的服务器发回一个 JSON 编码的响应,但您只向它传递一个值(在您的情况下为 191),$resource 似乎将其解释为一个字符串,然后将其拆分为单个字符数组(我不是 100% 了解原因的技术细节,但这是我的经验).因此,您需要做的是将包裹在 JSON 对象中的值发回.

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);
}

您需要执行以下操作:

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

然后当您的 $resource 调用返回时,只需访问响应的 value 属性,您就可以开始使用了.

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

P.S.这里的示例基于 Node/Express 后端,而不是 Spring,但我认为这仍然适用.

这篇关于Angular $resource 无法正确解析整数响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆