javascript 如何从 json 对象中删除 $promise 和 $resolved

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21831623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:47:03  来源:igfitidea点击:

How to remove $promise and $resolved from json object

javascriptangularjs

提问by user1184100

I'm using $resource in angular to get json object and its structure is defined below

我在 angular 中使用 $resource 来获取 json 对象,其结构定义如下

[
    {
        "id": 0,
        "name": "Type1"
    },
    {
        "id": 1,
        "name": "Type 2"
    }
]

after fetching the data .. console.log(jsonObject) gives me

获取数据后.. console.log(jsonObject) 给了我

[Resource, Resource, $promise: Object, $resolved: true]

How can I remove $promise & $resolved from the resulting object ? I tried angular.fromJson(json) but still I see that these objects still exist.

如何从结果对象中删除 $promise & $resolved ?我试过 angular.fromJson(json) 但我仍然看到这些对象仍然存在。

回答by Sergei Panfilov

I'm looking for the same answer, but at this moment I know only this ugly hack:

我正在寻找相同的答案,但此时我只知道这个丑陋的黑客:

To write a func like this:

要编写这样的函数:

function cleanResponse(resp) {
    return JSON.parse(angular.toJson(resp));
}

and call it in every single query (ugly, yep):

并在每个查询中调用它(丑陋,是的):

function getSmt() {
    Resource.get({}, function (data) {
        $scope.some = cleanResponse(data);
    }, function (responce) {
        //handle error
    })
}

I'll be happy if someone would teach me how to do it correctly

如果有人教我如何正确地做,我会很高兴

回答by callmejuggernaut

Example from my project

我的项目中的示例

Diary.getSharedWithMe(function(data) {
        delete data.$promise;
        delete data.$resolved;
        _self.sharedDiariesWithMe = data;
    }, function(error) {
        console.log(error)
    });

回答by Javarome

From this answer, it looks that yourResource.toJSON()is readily available.

这个答案来看,它看起来yourResource.toJSON()很容易获得。

回答by Arthur S.

Right, I've faced the same problem several times and always ended up using $http instead of $resource, however, today I decided to try and deal with this issue. I hope somebody will find this useful one day as well.

是的,我已经多次遇到同样的问题,最终总是使用 $http 而不是 $resource,但是,今天我决定尝试解决这个问题。我希望有一天有人也会发现这很有用。

So, after you receive your object with $promise inside of it, what you do is just use angular.copy(data), like so:

因此,在您收到包含 $promise 的对象后,您要做的就是使用angular.copy(data),如下所示:

someService.getSomething($scope.someId).$promise.then(function (data) {
    if (data) {
        $scope.dataWithoutPromise = angular.copy(data);
    }
});

After that, you will see that your dataWithoutPromisejust contains the objects that you need, and $promise and $resolved are gone.

之后,您将看到您的dataWithoutPromisejust 包含您需要的对象,而 $promise 和 $resolved 消失了。

回答by Arnaud Huveners

I'm facing the same issue. In fact, you simply have to use the same version of angular and angular-resource and it will work like a charm. Hope it helps !

我面临同样的问题。事实上,你只需要使用相同版本的 angular 和 angular-resource ,它就会像魅力一样工作。希望能帮助到你 !

回答by Geoff

Short answer : angular.fromJson(angular.toJson(resp)); This will remove all "angular specific" functions etc and will return you a clean data object.

简短回答:angular.fromJson(angular.toJson(resp)); 这将删除所有“角度特定”功能等,并将返回一个干净的数据对象。

回答by Mr.Bob

Please simply do this:

请简单地这样做:

jsonObject.$promise = undefined; jsonObject.$resolved = undefined;

jsonObject.$promise = 未定义;jsonObject.$resolved = undefined;

$promise and $resolved will not be removed but you will be able to do what you want.

$promise 和 $resolved 不会被删除,但你可以做你想做的。

回答by Matt Way

Are you using isArrayor .query()with your $resourceobject?

您是在使用isArray还是.query()与您的$resource对象一起使用?

From the $resource docs: isArray – {boolean=} – If true then the returned object for this action is an array.

从 $resource 文档: isArray – {boolean=} – If true then the returned object for this action is an array.

UPDATE:

更新:

If you are using $resourcecorrectly, some options you have are:

如果您使用$resource正确,您可以选择的一些选项是:

1) Have the backend return the data contained within an object, eg. { data: [] }rather than just an array.

1)让后端返回对象中包含的数据,例如。{ data: [] }而不仅仅是一个数组。

2) If that is not possible, use the callback from the $resource.query(), eg.

2)如果这是不可能的,请使用来自 的回调$resource.query(),例如。

MyResource.query({ myParams: 'something'}, function(result) {
    // Do something with the plain result
});

回答by Shar678

I did this quick reusable method for angular.toJson(Properties with leading $$ will be stripped):

我为angular.toJson做了这个快速可重用的方法 (以 $$开头的属性将被剥离):

yourApp.factory('Service', ['$resource', function ($resource) {
    return $resource('your/rest/api/path');
}]);

 yourApp.factory('commonServices', function () { 
         return {
                toJson : function(response){
                    return JSON.parse(angular.toJson(response));
                     //*or* 
                    //return angular.toJson(response);
                }
    });

And then something like this in your controller:

然后在你的控制器中是这样的:

 yourApp.controller('Controller', ['$scope', 'Service','commonServices',  
function ($scope, Service, commonServices) {
            Service.get().then(function (data) {
                $scope.myData = commonServices.toJson(data);
            });
        });

the more simple way is to add angular.toJsonin the controller

更简单的方法是在控制器中添加angular.toJson

 yourApp.controller('Controller', ['$scope', 'Service',  
function ($scope, Service, commonServices) {
            Service.get().then(function (data) {
                $scope.myData = angular.toJson(data);
            });
        });

回答by GedankenNebel

Try to code something like this in your service:

尝试在您的服务中编写这样的代码:

yourApp.factory('Service', ['$resource', function ($resource) {
    return $resource('your/rest/api/path');
}]);

And then something like this in your controller:

然后在你的控制器中是这样的:

yourApp.controller('Controller', ['$scope', 'Service', function ($scope, Service) {
    Service.get().then(function (data) {
        $scope.myData = data;
    });
});