In Angular, how do we map the JSON returned to the query parameters used for that particular response?

StackOverflow https://stackoverflow.com/questions/23553886

  •  18-07-2023
  •  | 
  •  

Domanda

I have created a plunker http://plnkr.co/edit/QojbqMNoDm9jHh2mFtVw?p=info to demonstrate what I am trying to do. It has two RESTful apis,

  1. First one returns name of moms (Mother's day is coming up :)) as strings
  2. The second one returns the kids names for a given mom in the URI.

I have the Kids api invoked in a for loop. I would like to create a new JS object having the name of the mom and her children. But I cannot be sure that array of kids and array of moms are at the same index since the REST calls can return in any order. How do I know the mother, when I get the kids name?

 var aMom = {
  name : "Amy Ape",
  "kids": ["Andy Roberts", "Allen Scott", "Amin Aslam"]
};

Thank you for your help.

È stato utile?

Soluzione

Fork of your plunker: http://plnkr.co/edit/yeP4zfi79KFHTHzBLxK5

I changed things around a little bit, added the kids object to the moms array (converted this to array, it was easier). The tricky bit is getting the index into the inner function, like this:

    for (var i=0; i < $scope.data.moms.length; i++) {
          (function(index) {
          Kids.get({'mom_name': $scope.data.moms[i].name}, function(response_two) {
          }).$promise.then(
            function kids_success(value) {
              $scope.data.moms[index].kids = value;
            }, 
            function kids_error(error) {
              $scope.data.status.push("kids service returned error="+error.data+error.status+error.statusText);
            }
          )
        })(i);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top