Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS-ForEach不循环 问题_Javascript_Jquery_Arrays_Angularjs_Foreach - Fatal编程技术网

Javascript AngularJS-ForEach不循环 问题

Javascript AngularJS-ForEach不循环 问题,javascript,jquery,arrays,angularjs,foreach,Javascript,Jquery,Arrays,Angularjs,Foreach,我有一个AngularJS应用程序,出于某种原因,我的一个forEach循环无法工作。当按钮上的a函数单击时,循环似乎工作,但在初始加载时它不工作 代码 因此,我已经为页面正确设置了控制器。我正在调用我的服务中的一个函数,该函数触发我的API并返回一个数组: 控制器 var holidaysnew = getUserEventsById.getUserEventsById(); 服务 app.service('getUserEventsById', function ($http) {

我有一个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;
};
});
因此,在初始页面加载时,holidays新建成功命中,是一个假日数组。行的下方是我的
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
是数组吗

编辑2:

以下是返回到服务的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响应时出错。数组的填充发生在return语句之后,因为REST调用是异步的。尝试将不起作用的循环移动到它自己的函数中,然后在REST成功回调中调用该函数,或者返回承诺并在成功回调中解决它

回报承诺:

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)
        });
    });
});

更好的解决方案/方法是从
resolve
调用
api

angular
    .module('app')
    .config(config);

function config($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'yourTemp.html',
            controller: 'Main',
            controllerAs: 'vm',
            resolve: {
                getUserEventsById: function(getUserEventsById){
                    return getUserEventsById.getUserEventsById()
                }
            }
        });
}

angular
    .module('app')
    .controller('Main', Main);

Main.$inject = ['getUserEventsById'];
function Main(getUserEventsById) {
      var vm = this;
      vm.yourdata = getUserEventsById.data;
}

现在,您可以在
vm.yourdata
上运行
forEach
循环,这样运行会很好。

更改服务以返回
$http
承诺,但也可以在服务本身中执行您需要的所有数据操作,以创建日历事件并返回这些事件

success
不赞成使用
then()
承诺链回调

更为传统的方法如下所示:

app.service('getUserEventsById', function($http, $q) {

  this.getUserEventsById = function() {

    var requestPromise = $http.get("url")
      .then(function(response) {
        var holidays = [];
        var results = response.data.GetAllEventsByUserResult
        for (var key in results) {
          if (results.hasOwnProperty(key)) {
            holidays.push(results[key])
          }
        }
        // return holidays array to next `then()`
        return holidays;
      }).then(function(holidays) {
        var holidayEvents = holidays.map(function(hol) {
          // make sure to inject `$filter` in service
          return {
            end: $filter('dateFilter')(hol.HOLIDAY_END),
            start: $filter('dateFilter')(hol.HOLIDAY_START),
            title: hol.HOLIDAY_TITLE,
            color: $filter('colorEventFilter')(hol.HOLIDAY_EVENT_STATE_ID)
          }

        });
        // return the events array to next `then()`
        return holidayEvents;

      });
    // return the `$http` promise to controller
    return requestPromise;

  };
});
然后在控制器中,您所需要的就是

getUserEventsById.getUserEventsById().then(function(holidayEvents){
    $scope.eventSources[0].events = holidayEvents;
}).catch(function(){

   // do something if promise chain has a rejection
})

$http
是异步的…在返回的数组被填充之前,您无法在其上循环。服务中没有
$scope
。。。当然,要用这个承诺——我已经改变了它来使用回调,但是一个承诺也许更好,肯定是更好的,需要考虑如果请求失败会发生什么,在控制器上有一个完全断开的连接,它没有办法捕获失败。我在一个版本中添加了一个返回承诺的版本。未经测试,所以如果您看到任何明显的错误,请告诉我,我会修复!不幸的是,这是一种反模式
$http
本身返回一个承诺,
success
被弃用(请参阅文档),赞成使用
then()
promise chainIdea是好的,但仍然不能保证服务请求已经完成,或者可能失败。解析仍然返回空数组,因为不管请求是否成功,服务都会返回空数组…不是空数组promise@charlietfl:如果承诺失败,控制器将不会实例化,路由将被拒绝。。。否则您的视图将被加载,并且一切都按预期工作。。。解决返回一个承诺。。。如果我错了,请纠正我…重点是没有失败的承诺。OP不返回承诺,只返回空数组
返回假日。因此,无论
$http
是否成功,都会返回该值。
resolve
将永远不会被拒绝。另外,如果
$http
需要2秒钟,空数组仍将在controllerIts反模式中结束,以便在服务中执行数据操作。。。这个服务调用变得迟钝,因为你不能在其他需要不同数据的地方使用它,而不是在这里操纵数据。。。只是我的想法…@Thalaivar如果是这样,那么就很容易用更多的方法来设置服务,这些方法可以组合在服务中。大多数样式指南都会告诉您保持控制器的精简,并以适当的方式进行处理service@charlietfl很抱歉迟了答复。谢谢你回答我的问题,我的服务似乎有错误。
holidayEvents
数组没有填充?@charlietfl我刚刚修复了一些格式错误。控制台中没有错误,但事件根本没有加载到日历中?我有
控制台。在控制器中记录了
holidayEvents
,一切似乎都很好?那么数据正在发送给控制器?以及预期的格式?