答案 0 :(得分: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;
}
}
您可以在任何地方定义该功能,但服务将是一种干净的方式。
使用它:
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;
});
}
}