问题
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