问题
我有一个AngularJS应用程序,由于某种原因,我的一个forEach循环不起作用.循环似乎在单击按钮上的a函数时起作用,但在初始加载时它不起作用.
码
所以我正确地为页面设置了控制器.我正在调用我的服务中的一个函数,该函数触发我的API并返回一个数组:
调节器
var holidaysnew = getUserEventsById.getUserEventsById();
服务
app.service('getUserEventsById', function ($http) {
this.getUserEventsById = function () {
var holidays = [];
$http.get("http://localhost:9847/AceTracker.svc/GetAllEventsByUser?user_id=1").success(function (data) {
for (var key in data.GetAllEventsByUserResult) {
if (data.GetAllEventsByUserResult.hasOwnProperty(key)) {
holidays.push(data.GetAllEventsByUserResult[key])
}
}
});
return holidays;
};
});
所以在初始页面加载holidaynew成功命中并且是一系列假期.线下面是我的forEach循环,我想循环遍历holidaysnew但它似乎没有进入循环.
循环编码如下:
holidaysnew.forEach(function (hol) {
$scope.eventSources[0].events.push({
end: $filter('dateFilter')(hol.HOLIDAY_END),
start: $filter('dateFilter')(hol.HOLIDAY_START),
title: hol.HOLIDAY_TITLE,
color: $filter('colorEventFilter')(hol.HOLIDAY_EVENT_STATE_ID)
});
});
我有console.log的holidaysnew数组,它肯定会被填充.有谁能看到这个问题?
编辑:
该服务似乎没问题,并按预期返回阵列(见下文)
但是当$scope.eventSources [0] .events = holidayEvents;代码运行它实际上似乎没有设置事件.
holidayEvents是一个数组吗?
EDIT2:
以下是返回给服务的JSON示例:
{"GetAllEventsByUserResult":[{"HOLIDAY_END":"\/Date(1456358400000+0000)\/","HOLIDAY_EVENT_ID":1,"HOLIDAY_EVENT_STATE_ID":1,"HOLIDAY_START":"\/Date(1455926400000+0000)\/","HOLIDAY_TITLE":"Spain ","USER_ID":1},{"HOLIDAY_END":"\/Date(1454371200000+0000)\/","HOLIDAY_EVENT_ID":2,"HOLIDAY_EVENT_STATE_ID":2,"HOLIDAY_START":"\/Date(1454284800000+0000)\/","HOLIDAY_TITLE":"Italy ","USER_ID":1},{"HOLIDAY_END":"\/Date(1458000000000+0000)\/","HOLIDAY_EVENT_ID":3,"HOLIDAY_EVENT_STATE_ID":1,"HOLIDAY_START":"\/Date(1457568000000+0000)\/","HOLIDAY_TITLE":"Germany ","USER_ID":1},{"HOLIDAY_END":"\/Date(1481068800000+0000)\/","HOLIDAY_EVENT_ID":4,"HOLIDAY_EVENT_STATE_ID":3,"HOLIDAY_START":"\/Date(1480896000000+0000)\/","HOLIDAY_TITLE":"England ","USER_ID":1}]}
最佳答案 这看起来像处理您的REST响应时出错.由于REST调用是异步的,因此数组的填充发生在return语句之后.尝试将无效的循环移动到自己的函数中,然后在REST成功回调中调用该函数,或者返回Promise并在成功回调中解析它.
回复承诺:
app.service('getUserEventsById', function ($http, $q) {
this.getUserEventsById = function () {
var deferred = $q.defer();
var holidays = [];
$http.get("http://localhost:9847/AceTracker.svc/GetAllEventsByUser?user_id=1").then(function (data) {
for (var key in data.GetAllEventsByUserResult) {
if (data.GetAllEventsByUserResult.hasOwnProperty(key)) {
holidays.push(data.GetAllEventsByUserResult[key])
}
}
deferred.resolve(holidays);
});
return deferred.promise;
};
});
循环承诺:
holidaysnew.then(function(holidays) {
holidays.forEach(function (hol) {
$scope.eventSources[0].events.push({
end: $filter('dateFilter')(hol.HOLIDAY_END),
start: $filter('dateFilter')(hol.HOLIDAY_START),
title: hol.HOLIDAY_TITLE,
color: $filter('colorEventFilter')(hol.HOLIDAY_EVENT_STATE_ID)
});
});
});