使用angular.fromJson()进行JSON反序列化

时间:2015-10-14 19:28:00

标签: json angularjs

尽管AngularJS documentation for angular.fromJson很壮观,但我仍然不知道如何充分利用它。最初我刚刚将HTTP请求中的JSON数据响应直接分配给$scope变量。我最近注意到Angular有一个内置的fromJson()函数,这似乎是我想要使用的东西。如果我使用它,它是否更安全,我可以更容易地访问数据元素?

这就是我一直在做的事情:

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

我就是这样做的:

$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 个答案:

答案 0 :(得分:2)

将响应转换为json是没有意义的,因为它会为你提供角度。来自angular documentation of $http

  

Angular提供以下默认转换:

     

请求转换 $httpProvider.defaults.transformRequest$http.defaults.transformRequest):

     

如果请求配置对象的data属性包含对象,请将其序列化为JSON格式。

     

响应转换 $httpProvider.defaults.transformResponse$http.defaults.transformResponse):

     

如果检测到XSRF前缀,请将其删除(请参阅下面的“安全注意事项”部分)。   如果检测到JSON响应,则使用JSON解析器对其进行反序列化。