如果我从httpbackend为响应对象创建一个对象而不是数组'数据'它工作正常。但是一旦我把它变成一个数组(甚至是单个元素数组),它就不想工作并且给我一个错误,说未定义不是一个对象(评估' booking.Student.studentName')。下面是代码。有任何想法吗?是因为lodash不做这件事吗?
我的控制器中有以下功能
$scope.initBookings = function() {
return $http.get('/api/bookings').then(function(response) {
return $scope.bookings = _.map(response.data, function(booking) {
booking.studentName = booking.Student.studentName;
booking.slotDay = booking.Slot.day;
booking.slotTime = booking.Slot.time;
booking.subjectName = booking.Subject.name;
return booking;
});
});
};
我的测试如下
it('should store bookings into $scope.bookings and create a $scope.bookingsTable', function() {
expect(this.scope.bookings).toBeUndefined();
this.scope.initBookings();
this.httpBackend.expect('GET', '/api/bookings');
this.httpBackend.flush();
expect(this.scope.bookings).toBeDefined();
});
this.httpBackend.whenGET('/api/bookings').respond(function() {
return [
200, {
data: [
{
Student: {
studentName: 'John Die'
},
Slot: {
day: 'today',
time: 'now'
},
Subject: {
name: 'maths'
}
}, {
Student: {
studentName: 'Jane Die'
},
Slot: {
day: 'tomorrow',
time: 'before'
},
Subject: {
name: 'mathamatix'
}
}
]
}
];
});
它正在返回
Object{data: [Object{Student: ..., Slot: ..., Subject: ...}, Object{Student: ..., Slot: ..., Subject: ...}]}
答案 0 :(得分:0)
控制器功能很乱。
请注意,您正在奇怪地使用同步/异步代码从服务器获取数据。
为了使其更具可读性和可测试性,请将其完全重写为异步:
$scope.bookings = [];
$scope.initBookings = function() {
$http.get('/api/bookings').then(function(response) {
$scope.bookings = _.map(response.data, function(booking) {
var out = {
studentName: booking.Student.studentName,
slotDay: booking.Slot.day,
slotTime: booking.Slot.time,
subjectName: booking.Subject.name
};
return out;
});
});
};
$scope.initBookings();
lodash内部循环的主体将其他变量添加到其他变量中,因此在$scope.bookings
中推送的结果对象变为:
{
studentName,
Student:{
studentName
},
slotDay,
Slot: {
day,
time
},
slotTime,
subjectName,
Subject:{
name
}
}