Tips for accessing an array you've constructed in the $onInit() function within Angular-Fullstack

I am currently working on an Angular fullstack project that utilizes Babel and Angular 1.5.0.

The problem I am encountering is that I am trying to initialize an array (this.events = []) but unable to access this array in $onInit() where I need to populate data to be shown on ui-calendar. To work around this issue, I am using this.awesomeTesting = [];

My goal is to fill the this.events[] array with data from $http.get('/api/calendars/') inside $onInit(), but I can't figure out why I cannot target the array for data population.

What could I be doing wrong?

Below is the code snippet:

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

})();

Answer №1

To resolve the issue, I switched from using .forEach() to implementing a for loop. Despite this workaround, I remain curious about how the solution could be achieved with .forEach() instead.

Here is the modified code using a for loop:

for (var i = 0; i < this.awesomeTesting.length; i++) {

    this.events.push({
      title: this.awesomeTesting[i].title,
      start: this.awesomeTesting[i].start
    });
  }

Answer №2

If you're looking to clear the event array, consider using this.events = []; I trust this information will be beneficial.

Answer №3

Give this a shot:

Assign “that” to the current object and then replace this.events with that.events

`$onInit() {

*var that = this;*
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);

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

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

}`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I possess a certain input and am seeking a new and distinct output

I am looking to insert a word into an <input> and see an altered output. For example, Input = Michael Output = From Michael Jordan function modifyOutput() { var inputWord = document.getElementById("inputField").value; var outputText = "print ...

Is it possible to have a leaderboard stored in a database without requiring user

I am in the process of developing a game using Javascript that includes a leaderboard feature. Originally, my plan was to allow players to enter their name and then click a button to start the game. Since the game includes a countdown timer, I needed a w ...

Tips for displaying errors in React applications

Having trouble troubleshooting React (16.13.0) as I am not receiving any useful errors, just this message: Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for more info or switch to the non-minified dev en ...

Error: Trying to use 'Player' before it has been initialized

Recently, I have been utilizing ES6 syntax along with import/export on Nodejs using the ESM module loader. Everything was running smoothly until I encountered an error related to imports. Below are the error messages that popped up: joseph@InsaneMachine ...

Leveraging Azure's Machine Learning capabilities through a Javascript Ajax request

Has anyone successfully called the Azure Machine Learning webservice using JavaScript Ajax? Azure ML provides sample code for C#, Python, and R, but I'm struggling with JQuery Ajax. Despite my efforts, calling the webservice using JQuery Ajax result ...

What is the process for setting environment variables in a Svelte project?

I'm brand new to working with Svelte and I want to incorporate environment variables like base_url into different components. I've read that I can set up a store to hold these values, for example: const DataStore = writable([ { base_url: & ...

What is the process for transforming a nested dictionary in JSON into a nested array in AngularJS?

I am looking to create a form that can extract field values from existing JSON data. The JSON I have is nested with dictionary structures, but I would like to convert them into arrays. Is there a way to write a recursive function that can retrieve the key ...

The node sends a request to the API to retrieve data, which is then stored in an array. Subsequently, another request is

var UfcAPI = require('ufc-api'); var ufc = new UfcAPI({ version: '3' }); const fighterIdList = []; function fetchFighterIds() { ufc.fighters(function(err, res) { for (let i = 0; i < res.body.length; i++) { ...

Exploring AngularJS: handling objects, working with arrays, diving into JSON, and troubleshooting

Generating: In my Angular application, I utilize $scope.services to store a list of services. This variable holds an array of objects: $scope.services = [{ title : undefined, quantity : undefined, pricePerUnit : undefined, ...

The output from the console displays a variety of numbers (11321144241322243122)

Every time I attempt to log the number 11321144241322243122 into the console, it consistently converts to a different number 11321144241322244000. This issue persists both in node.js and the browser console. ...

What are the methods for incorporating reflection into three.js?

While working on a WebGL project using Three.js, I am aiming to incorporate a reflective cube surface that mimics the appearance of a mobile phone display. The surface should be able to reflect light while maintaining a black color scheme. ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

What is the best way to trigger a Quasar dialog from an outside component?

Currently, I am working with Vue.js 2.x + Quasar 1.x using http-vue-loader (no build tools required). I have placed a q-dialog in a separate component named MyComponent. However, when I try to include it in a parent component like this: <my-component&g ...

Click on the button to create a link and then seamlessly navigate there using a combination of ajax, php, and javascript

I am in need of a button that can trigger a php page through ajax. The purpose of this button is to open the client's email with a mailto link. The php page created generates an email containing an encrypted string that carries credentials for access ...

Utilizing Ajax for Efficiently Updating a Singular Field within a Designated Object

How can I use Ajax to Update a Single Field in a Specific Object? I have a table in my postgres database with numerous records. I am interested in using a jquery Ajax request to update just one field in a particular object within that table. Is it possibl ...

Disable menu bar | customize menu bar in electronJS

I am developing an Angular application with Electron.js. Due to the specific design requirements of my app, which is browser-based, I do not require or want the default Electron.js menu or menu bar to be displayed. Is there a way to remove it from my app ...

Retrieve the value of a field from a Formik form integrated with Material UI

I've been working on a way to disable a checkbox group depending on the selected value of a radio group. I took inspiration from the technique outlined in the final section of the Formik tutorial. Using React context has definitely helped clean up the ...

Placing text inside a designated element on a different web page upon clicking a button

Imagine a scenario where a user is browsing a website and lands on the 'prices' page. They come across a product that catches their eye and decide to click on the associated button. This action redirects them to the 'contact us' page, w ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Rails controller did not receive the Ajax call

I have noticed that when I make an Ajax call using jQuery, the data is always transmitted (status 200), but there are times when it's not properly received by the Rails controller. The data is sent correctly, but most of the time the controller respon ...