1

Despite from the AngularJS documentation for angular.fromJson being spectacular, I still don't know how to use it to its fullest potential. Originally I have just been directly assigning the JSON data response from an HTTP request to a $scope variable. I've recently noticed that Angular has a built-in fromJson() function, which seems like something I'd want to use. If I use it, is it safer and can I access data elements easier?

This is how I've been doing it:

$http({
    method: 'GET',
    url: 'https://www.reddit.com/r/2007scape.json'
}).then(function success(response) {
    var mainPost = response; // assigning JSON data here
    return mainPost;
}, function error(response) {
    console.log("No response");
});

This is how I could be doing it:

$http({
    method: 'GET',
    url: 'https://www.reddit.com/r/2007scape.json'
}).then(function success(response) {
    var json = angular.fromJson(response); // assigning JSON data here
    return json;
}, function error(response) {
    console.log("No response");
});
1
  • response should already be parsed to array or object ..not json string Commented Oct 14, 2015 at 19:37

1 Answer 1

2

It is pointless to convert the response to json as angular does it for you. From angular documentation of $http:

Angular provides the following default transformations:

Request transformations ($httpProvider.defaults.transformRequest and $http.defaults.transformRequest):

If the data property of the request configuration object contains an object, serialize it into JSON format.

Response transformations ($httpProvider.defaults.transformResponse and $http.defaults.transformResponse):

If XSRF prefix is detected, strip it (see Security Considerations section below). If JSON response is detected, deserialize it using a JSON parser.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.