AngularJS: get promise value without internal properties

92 views Asked by At

Ok, another promise-related question (I see there are already quite a few of them). I'm trying to get promise result from endpoint and use it in ng-repeat, first is the typical response from endpoint:

{"ebbe5704-4ea5-470e-8ab9-102ee8ca457f":"Foo",
 "e380a6f7-2f88-46bb-bd54-251719353627":"Bar"
}

here's how I get it from promise:

RequestService.getValues().$promise.then(function(res) {
    vm.result = res;
});

and here I render it in HTML:

<p ng-repeat="i in vm.result">{{i}}</p>

The problem is the rendered view contains internal fields of the promise ($promise and $resolved): enter image description here

Am I doing something wrong? Is there any less ugly way instead of filtering through result keys?

UPD: RequestService.getValues is a $resource, so can be replaced like this:

$resource("/rest/", null, {
    getValues: {
        url: "/rest/values/",
        method: "GET"
    }
}).getValues().$promise.then(function(res) {
    vm.result = res;
    console.log("RES:", res);
});

2

There are 2 answers

0
Piou On

The problem here is that you are iterating with ng-repeat over an object (so getting the keys of each property of the object) and not over an array.

AngularJS resources are made to be used with ng-repeat only if the returned resource is an array. When facing an object ng-repeat uses something like for(var key in obj) whereas when facing an array it uses the indexer to loop as following for(var i=0; i<arr.length; i++). Thus, with an array, it is skipping other properties like $promise and so.

What you should do is implement a custom filter that will skip angular decorators methods away from the ng-repeat iteration:

$scope.skipResourceFn= function(key)
{
    // is it an angular decorator (starting with '$' char):
    return key.indexOf('$') != 0;
};

Then in your template:

<p ng-repeat="i in vm.result | filter:skipResourceFn">{{i}}</p>
0
georgeawg On

One can use the $http service to get the object:

var config = {
    url: "/rest/values/",
    method: "GET"
};

$http(config).then(function(response) {
    var data = response.data;
    vm.result = data;
    console.log("RES:", data);
});

The $http service does not append additional properties to an object.