使用angular.fromJson()进行JSON反序列化
尽管AngularJS非常壮观,但我仍然不知道如何充分利用它的潜力。最初,我只是将来自HTTP请求的JSON数据响应直接分配给使用angular.fromJson()进行JSON反序列化,json,angularjs,Json,Angularjs,尽管AngularJS非常壮观,但我仍然不知道如何充分利用它的潜力。最初,我只是将来自HTTP请求的JSON数据响应直接分配给$scope变量。我最近注意到Angular有一个内置的fromJson()函数,这似乎是我想要使用的。如果我使用它,它会更安全吗?我能更容易地访问数据元素吗 我就是这样做的: $http({ method: 'GET', url: 'https://www.reddit.com/r/2007scape.json' }).then(function suc
$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");
});
我可以这样做:
$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");
});
将响应转换为json是毫无意义的,因为angular会为您这样做。发件人: 角度变换提供以下默认变换: 请求转换(
$httpProvider.defaults.transformRequest
和$http.defaults.transformRequest
):
如果请求配置对象的数据属性包含对象,则将其序列化为JSON格式
响应转换($httpProvider.defaults.transformResponse
和$http.defaults.transformResponse
):
如果检测到XSRF前缀,请将其去掉(请参阅下面的安全注意事项部分)。
如果检测到JSON响应,则使用JSON解析器对其进行反序列化
响应
应已解析为数组或对象..而不是json字符串