Ioan Adrian Duliba Ioan Adrian Duliba - 5 months ago 11
AngularJS Question

How to get a user and attach it to a review, then send the result to view using JavaScript?

$http.get("api/location/getReviews/" + $routeParams.id)
.success(function (data) {
$scope.reviews = {};
$scope.reviews = data;
angular.forEach($scope.reviews,
function (value, index) {
$http.get("api/user/" + value.UserId)
.success(function (user) {
$scope.value.User = user;
});
});
});


I have the following code and what I am trying to do is to get the user
from
userId
, attach it to a review, and send it into view because my review has a
userId
and I need the user's email. When I list the reviews, I want to show the email and not the id, but I don't know how to do this. It gives me cannot read property or undefined User.

Anyone can explain what happen?

Answer

You can place the user object returned from the API call in the loop into the indexed review object in the reviews Array this way :

    angular.forEach($scope.reviews, function (value, index) {

            $http.get("api/user/" + value.UserId)
            .success(function (user) {

                  $scope.reviews[index].User = user;

            });

   });