Консоль, отображающая информацию о 4 объектах, когда в моем массиве только 1 объект

0

У меня есть следующий код в angularjs:

TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;

                var events = [];

                 angular.forEach(vm.data, function(value,key) {

                    var eventName = value.name;
                    var startDate = new Date(value.startDate);
                    var endDate = new Date(value.endDate);

                    var selectedStartingTime =new Date(value.startTime * 1000 );
                    var selectedEndingTime = new Date(value.endTime * 1000);

                    //timing is not right, needs fixing
                    startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
                    endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());                     
                    // console.log(startTime);
                    events.push({
                        title: 'Event -' + eventName,
                        startTime: startTime,
                        endTime: endTime,
                        allDay: false

                    });

            console.log(eventName);
            console.log(events);
            // console.log(value);

             //value is the object!!
            })
             return events;
             $scope.$broadcast('eventSourceChanged',$scope.eventSource);

            })

         }

Каждый раз, когда цикл forEach проходит через мой массив объектов, vm.data, консоль печатает это:

Изображение 174551

Мои вопросы:

1) Почему детали из 4 объектов печатаются? Означает ли это, что для каждого объекта в массиве он содержит 4 других объекта?

2) Соответствует ли каждый объект соответствующим событиям []?

3) Если ответ на вопрос 2 нет, что я должен сделать, чтобы его решить?

EDIT: Обновлен код для использования обещания вернуть массив событий:

    //Calendar Controller
  .controller('CalendarCtrl', function ($scope,TimeSlotsModel,$rootScope,$q) {
    var vm = this;


    function goToBackand() {
        window.location = 'http://docs.backand.com';
    }

    function getAll() {
        TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;
            });
    }

    function clearData(){
        vm.data = null;
    }

    function create(object) {
        TimeSlotsModel.create(object)
            .then(function (result) {
                cancelCreate();
                getAll();
            });
    }

    function update(object) {
        TimeSlotsModel.update(object.id, object)
            .then(function (result) {
                cancelEditing();
                getAll();
            });
    }

    function deleteObject(id) {
        TimeSlotsModel.delete(id)
            .then(function (result) {
                cancelEditing();
                getAll();
            });
    }

    function initCreateForm() {
        vm.newObject = {name: '', description: ''};
    }

    function setEdited(object) {
        vm.edited = angular.copy(object);
        vm.isEditing = true;
    }

    function isCurrent(id) {
        return vm.edited !== null && vm.edited.id === id;
    }

    function cancelEditing() {
        vm.edited = null;
        vm.isEditing = false;
    }

    function cancelCreate() {
        initCreateForm();
        vm.isCreating = false;
    }

    // initialising the various methods
    vm.objects = [];
    vm.edited = null;
    vm.isEditing = false;
    vm.isCreating = false;
    vm.getAll = getAll;
    vm.create = create;
    vm.update = update;
    vm.delete = deleteObject;
    vm.setEdited = setEdited;
    vm.isCurrent = isCurrent;
    vm.cancelEditing = cancelEditing;
    vm.cancelCreate = cancelCreate;
    vm.goToBackand = goToBackand;
    vm.isAuthorized = false;


    //rootScope refers to the universal scope, .$on is a receiver for the 
    //message 'authorized'
    $rootScope.$on('authorized', function () {
        vm.isAuthorized = true;
        getAll();
    });

    $rootScope.$on('logout', function () {
        clearData();
    });

    if(!vm.isAuthorized){
        $rootScope.$broadcast('logout');
    }

    initCreateForm();
    getAll();


    $scope.calendar = {};
    $scope.changeMode = function (mode) {
        $scope.calendar.mode = mode;
    };

    $scope.loadEvents = function () {
        $scope.calendar.eventSource = getEvents();
        $scope.$broadcast('eventSourceChanged',$scope.eventSource);

    };

    $scope.onEventSelected = function (event) {
        console.log('Event selected:' + event.startTime + '-' + event.endTime + ',' + event.title);
    };

    $scope.onViewTitleChanged = function (title) {
        $scope.viewTitle = title;
    };

    $scope.today = function () {
        $scope.calendar.currentDate = new Date();
    };

    $scope.isToday = function () {
        var today = new Date(),
            currentCalendarDate = new Date($scope.calendar.currentDate);

        today.setHours(0, 0, 0, 0);
        currentCalendarDate.setHours(0, 0, 0, 0);
        return today.getTime() === currentCalendarDate.getTime();
    };

    $scope.onTimeSelected = function (selectedTime) {
        console.log('Selected time: ' + selectedTime);
    };


    function getEvents(object){

      var deferred = $q.defer();

        TimeSlotsModel.all()
            .then(function (result) {
                vm.data = result.data.data;

                var events = [];

                 angular.forEach(vm.data, function(value,key) {

                    var eventName = value.name;
                    var startDate = new Date(value.startDate);
                    var endDate = new Date(value.endDate);

                    var selectedStartingTime = new Date(value.startTime * 1000 );
                    var selectedEndingTime = new Date(value.endTime * 1000);

                    //timing is not right, needs fixing
                    startTime = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(),selectedStartingTime.getHours(), selectedStartingTime.getUTCMinutes());
                    endTime = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(),selectedEndingTime.getUTCHours(), selectedEndingTime.getUTCMinutes());                     
                    // console.log(startTime);
                    events.push({
                        title: 'Event -' + eventName,
                        startTime: startTime,
                        endTime: endTime,
                        allDay: false

                    });
            // console.log(eventName);
            // console.log(events);
            // console.log(value);
            // console.log(key);
            // console.log(value);

             //value is the object!!
            })

            deferred.resolve(events);

            // return events;


            })
            return deferred.promise;
            console.log(deferred.promise);


         }
  • 1
    Вы по-прежнему возвращаете объект из асинхронного вызова функции ( .all().then() ), который не работает: почему моя переменная не изменяется после того, как я изменил ее внутри функции? - асинхронная ссылка на код ; Также ничего после return ... не достижимо и поэтому не выполнено
  • 1
    Предупреждение: я не читал ваш код подробно, но: эти маленькие синие i рядом с зарегистрированными объектами означают что-то вроде «Объект был переоценен, когда детали были расширены» (наведите курсор на него, чтобы получить всплывающую подсказку для точная формулировка) - то есть он мог быть изменен после того, как был зарегистрирован, и вы видите обновленный объект в журнале.
Показать ещё 5 комментариев
Теги:
ionic-framework
arrays
ionic

1 ответ

1
Лучший ответ

[! Удален старый ответ]

Я считаю, что Джеймс прямо здесь, консоль может быть виновником, я просто воспроизвел такое же поведение. Изображение 174551

Ещё вопросы

Сообщество Overcoder
Наверх
Меню