ngResource save()方法的回调参数是什么

编程入门 行业动态 更新时间:2024-10-28 08:24:42
本文介绍了ngResource save()方法的回调参数是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在将我的角度代码从使用$ http重构为ngResource.

I'm refactoring my angular code from using $http to ngResource.

我曾经在服务中使用过这样的代码:

I used to have code like this in my service:

svc.login = function(username, password) { return $http.post(apiEndpoint + 'authenticate', { username: username, password: password }) .then(function(val) { console.log("user token:", val.data); svc.token = val.data; }); };

打印的用户令牌将是jwt令牌.现在,我尝试将代码重构为如下形式:

The user token printed will be a jwt token. Now I try to refactor the code to something like this:

svc.login = function(username, password) { svc.authenticateApi().post(apiEndpoint + 'authenticate', { username: username, password: password }, function(val) { console.log("user token:", val); svc.token = val; }, function(res) { console.log("error:", res.status + " " + res.statusText); }); };

但是,它不起作用,因为传递给第一个回调的参数 val 不再是令牌本身,而是包含如下字符串数组的对象:

However, it doesn't work because the parameter val passed to the first callback is no longer the token itself but a object which contains a string array like this:

处理post方法返回的数据的标准方法是什么?(在这种情况下,帖子的定义与此资源上的 save 相同)

What's the standard way to handle data returned from post method? (in this case post is defined the same as save on this resource)

推荐答案

我认为问题来自transformRespose

I think the issue comes from transformRespose

transformResponse – {function(data,headersGetter)| Array.} –转换函数或此类函数的数组.转换功能需要http响应正文和标头,并返回其转换后的(通常反序列化)版本.默认情况下,transformResponse将包含一个用于检查响应是否看起来像JSON的函数字符串,并使用angular.fromJson将其反序列化.为了防止这种情况行为,将transformResponse设置为一个空数组:transformResponse:[]

transformResponse – {function(data, headersGetter)|Array.} – transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version. By default, transformResponse will contain one function that checks if the response looks like a JSON string and deserializes it using angular.fromJson. To prevent this behavior, set transformResponse to an empty array: transformResponse: []

尝试将您的响应转换为json:

try transforming your response into a json:

transformResponse: function (data) { return { token: angular.fromJson(data) }

更多推荐

ngResource save()方法的回调参数是什么

本文发布于:2023-11-16 21:43:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   参数   方法   ngResource   save

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!