AngularJS: finding an array returned from a promise in a service

I have an AngularJS service, it retrieves an array with JSON objects from the server.

In the service, I need the function "getElementByID (ID)" from the list that was called by the service. (or get the XY item)

My problem is that the list is not there when I start the search. It does not seem to work to resolve the promise in the service itself - is it always necessary to decide from the outside?

I created Plunker to describe the problem here: http://plnkr.co/edit/Hlyg3mGPi7RKFHmcK1ZM?p=preview

How can I find an array that is a promise in a service?

Thank you for your help!

+4
source share
1 answer

, - .then, , .

:

// return if in a service method
var p = $http.get("http://jsonurl").then(function(result){
    return result.filter(function(el){ return el.id === "foo"});
});

p.then(function(value){
   // value is an array that contains only elements with property `id === "foo"`
});

, , , :

var data = null;
function getData(){
    return $q.when(data || $http.get("http://jsonurl")).then(function(val){
        return data = val; // cache and return the result;
    }); // either data, or cached data
}

getByPredicate :

function get(predicate){
     return getData().then(function(arr){
          return arr.filter(predicate);
     });
}

:

get(function(el){ return el.id === "foo"; }).then(function(values){
    //values is all the array elements with an id property whose value is foo.
});
+2

Source: https://habr.com/ru/post/1540554/


All Articles