ngResource save()方法的回调参数是什么 [英] What's the parameter for ngResource save() method's callback

查看:47
本文介绍了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()方法的回调参数是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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