Search code examples
javascriptarraysangularjsecmascript-6angular-fullstack

How to target constructed array from within $onInit() using angular-fullstack


I'm working on a angular fullstack project which uses Babel and Angular 1.5.0.

The issue is that when I'm constructing an array (this.events = []) I cannot target this array on $onInit() where I'm supposed to populate data to be displayed on ui-calendar. I do this on this.awesomeTesting = [];

So I need to populate this.events[] array with data from $http.get('/api/calendars/') inside $onInit() but I don't understand why I cannot target the array so I can populate the data.

What am I doing wrong?

Here is my code:

'use strict';

(function() {

class MainController {

  constructor($http, $scope, socket, uiCalendarConfig) {
    this.$http = $http;
    this.socket = socket;
    this.awesomeThings = [];
    this.awesomeTesting = [];
    this.events = [];
    this.events.splice(0, this.events.length);
    this.eventSources = [this.events];
    console.log(this.eventSources);


    /* config object */
    $scope.uiConfig = {
      calendar:{
        height: 450,
        editable: true,
        header:{
          left: 'month',
          center: 'title',
          right: 'today prev,next'
        },
        dayClick: $scope.alertEventOnClick,
        eventDrop: $scope.alertOnDrop,
        eventResize: $scope.alertOnResize
      }
    };

    $scope.$on('$destroy', function() {
      socket.unsyncUpdates('thing');
    })
  }

  $onInit() {
    this.$http.get('/api/things').then(response => {
      this.awesomeThings = response.data;
      this.socket.syncUpdates('thing', this.awesomeThings);
    });

    this.$http.get('/api/calendars').then(response => {
      this.awesomeTesting = response.data;

      this.awesomeTesting.forEach(function (objectItem) {
        console.log('displays property in each object: ', objectItem.title);

        this.events.push({
          title: objectItem.title,
          start: objectItem.start
        });

      });
      this.socket.syncUpdates('calendar', this.awesomeTesting);
    });
  }

  addThing() {
    if (this.newThing) {
      this.$http.post('/api/things', { name: this.newThing });
      this.newThing = '';
    }
  }

  deleteThing(thing) {
    this.$http.delete('/api/things/' + thing._id);
  }
}

angular.module('myApp')
  .component('main', {
    templateUrl: 'app/main/main.html',
    controller: MainController
  });

})();

Solution

  • I fixed the issue by making a for loop instead of .forEach() but I still would like to know the answer how it could be done with .forEach()?

    The solution with for loop:

    for (var i = 0; i < this.awesomeTesting.length; i++) {
    
        this.events.push({
          title: this.awesomeTesting[i].title,
          start: this.awesomeTesting[i].start
        });
      }