I'm building an application where i list events in an html table. An event holds some information about itself but also a user-id, this user-id is the identifier for the user in the mongodb database i'm using
I want to use the $http service provided by angular to first get the events, then looping through the data in the response and issue another get to fetch the user object for each user-id. Every event carries exactly one user-id. The user object is then appended onto the existing event object as a nested object.
However when i do this the user-id variable i use for the calls turns out to be unassigned, as the http calls are async. I've read something about trailing/chaining the calls but i don't get it to work.
Below is the code i've tried amongst what seems to be 100 tries..
Controller
"use strict";
(function () {
var app = angular.module("app-test");
app.controller("testController", function ($scope, $log, $http, $route) {
var getAllQualityEvents = function () {
return $http.get("http://localhost:5001/api/qualityevent")
.then(function (response) {
return response.data;
});
};
var getUserForEvents = function (data) {
var result;
for (var d in data) {
$http.get("http://localhost:5001/api/user/" + d.userId)
.then(function (response) {
$scope.qualityEvent[d]["user"] = response.data;
});
};
};
// Run every loop.
getAllQualityEvents()
.then(function (data) {
$scope.qualityEvent = data;
getUserForEvents(data);
});
});
})();
Html document (only the path using the controller)
<div class="row">
<div class="col-xl">
<h1>Test events</h1>
</div>
</div>
<div class="row">
<div class="col-xl">
<table class="table">
<thead>
<tr>
<th>Username</th>
<th>User Id</th>
<th>Something</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="qualityEvent in qualityEvents" class="{{qualityEvent.isQualityOk ? 'bg-success' : 'bg-danger'}}">
<td scope="row">{{qualityEvent.user}}</td>
<td>{{qualityEvent}}</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
Error message
My api returning an error message telling me "undefined" is not a valid id.
getUserForEvents()
方法中的data
很可能是数组,因此您需要data[d].userId
而不是d.userId
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.