How to remove $promise and $resolved from json obj

2020-08-09 08:26发布

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

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

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

[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.

10条回答
▲ chillily
2楼-- · 2020-08-09 09:08

Please simply do this:

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

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

查看更多
Evening l夕情丶
3楼-- · 2020-08-09 09:09

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;
    });
});
查看更多
干净又极端
4楼-- · 2020-08-09 09:15

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

查看更多
一夜七次
5楼-- · 2020-08-09 09:18

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 !

查看更多
forever°为你锁心
6楼-- · 2020-08-09 09:20

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

查看更多
闹够了就滚
7楼-- · 2020-08-09 09:21

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.

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

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

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

查看更多
登录 后发表回答