What's the parameter for ngResource save() method's callback

淺唱寂寞╮ 提交于 2019-12-24 08:19:43

问题


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

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

        };

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:

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)


回答1:


I think the issue comes from transformRespose

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: []

try transforming your response into a json:

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


来源:https://stackoverflow.com/questions/37326985/whats-the-parameter-for-ngresource-save-methods-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!