解析JSON(访问$ Ref)Angular [英] Parsing JSON (accessing $Ref) Angular
本文介绍了解析JSON(访问$ Ref)Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在解析JSON数据时遇到问题.在对象2上,我将拥有"t_quartier",而该值只是指向对象1的引用. 如果我在商品2上,该如何获得该值?
I have a problem on parsing of my JSON data. On my object 2, I would have the "t_quartier" while the value is just a reference that points to the object 1. How can I get this value if I'm on my item 2?
非常感谢
推荐答案
您可以使用:
angular.module('app').service('commonService', commonService);
function commonService() {
//DFS for fixing JSON references
var elements = {}
this.fixReferences = function (json) {
var tree = json;
for (var x in tree) {
if ((typeof (tree[x]) === 'object') && (tree[x] !== null)) {
var result = dfsVisit(tree[x]);
tree[x] = result;
}
}
return tree;
}
function dfsVisit(tree) {
for (var x in tree) {
if ((typeof (tree[x]) === 'object') && (tree[x] !== null)) {
var result = dfsVisit(tree[x]);
tree[x] = result;
}
}
if (tree["$ref"] !== undefined) {
var ref = tree.$ref;
if (elements[ref] !== undefined) {
tree = elements[ref];
}
} else if (tree["$id"] !== undefined) {
var element = tree;
elements[element.$id] = element;
}
return tree;
}
}
您可以在任意位置定义该功能,但是使用服务是一种干净的方法.
You could define that function wherever you want but a service would be a clean way.
使用它:
angular.module('app').factory('yourService', yourService);
/*@ngInject*/
function yourService($http, commonService) {
var service = {
get: get
};
return service;
function get() {
return $http.get('Your url').then(function (response) {
var fixedData = commonService.fixReferences(response.data);
return fixedData;
});
}
}
这篇关于解析JSON(访问$ Ref)Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文