且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析JSON(访问$ Ref)Angular

更新时间:2023-09-30 09:47:58

您可以使用:

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