我正在尝试检索一组用户信息(通过搜索名字),并返回名字和预订日期(从mongoDB,mongoose模式使用date:Date)。名是type = text,预订日期是type = date。它返回未定义的日期,错误消息为错误:[ngModel:datefmt]预期`2017-11-06T16:00:00.000Z为date。我读了其他问题/答案,这是因为type = date需要一个对象,但是JSON返回一个字符串。
我是Angular JS的新手,我尝试了建议的方法,但没有结果。我不知道缺少什么。根据我的代码欣赏任何特定的指针
的HTML
<form name="updateBookingsForm" ng-repeat="booking in ctrl.bookings" novalidate>
<input name="firstname" type="text" ng-model="booking.firstname" class="form-control" required>
<input name="date" type="date" ng-model="booking.date" class="form-control" required>
</form>
控制者
self.searchAllBookings = function () {
paAppAPI.searchAllBookings(self.term).then(function (result) {
console.log(result); //returns array and date undefined
self.bookings = result;
}
}).catch(function (err) {
console.log(err);
if (err.status == 404) {
self.message = "No bookings found";
self.showMessage = true;
}
});
}
服务
self.searchAllBookings = function (term) {
var defer = $q.defer();
$http.get("/api/booking?keyword=" + term).then(function (result) {
console.log(result); //returns array but date undefined
if (result.status == 200) {
defer.resolve(result.data);
}
else {
defer.resolve(null);
}
}).catch(function (err) {
console.log(err);
defer.reject(err);
});
return defer.promise;
}
服务器
app.get("/api/booking?", function (req, res) {
console.log("Search booking > " + req.query.keyword);
var keyword = req.query.keyword;
Booking.find({
"firstname" : new RegExp('^'+keyword+'$', "i")
}, (err, result) => {
if (err) {
console.log(err);
}
res.status(200).json(result);
console.log(result);
// { _id: 5a1a4e1238dfaa65e5fa59a2,
// firstname: 'Emily',
// date: 2017-11-20T16:00:00.000Z,
// __v: 0 },
console.log(result[0].date); //2017-11-06T16:00:00.000Z
});
});
我假设self.bookings
是一个数组。如果是这样,则需要先将其循环,然后再将字符串转换为日期。
然后,如果日期未定义,请指定当前日期。否则,将字符串转换为Date。
.then(function (result) {
console.log(result); //returns array but date is undefined
self.bookings = result;
for(var i=0; i< self.bookings.length; i++){
self.bookings[i].date = new Date(self.bookings[i].date) : Date.now())
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句