Access the elements within arrays without using the square brackets

I am trying to access data from a list, but I am having trouble using square brackets []. The getTalonPaie function calls the get method from the HttpClient service and returns an observable with multiple values. However, when I try to store these values in my array, it ends up being a strange empty list with data inside.

onSubmit(): void {
    this.listeTalonPaie = Array<number>(1);
    const test = [1, 2, 3];

    this.listeIndividus = this.indS.listeIndividu;
    this.listeIndividus.forEach(ind => {
      // The following function returns an observable containing multiple objects 
      // which I want to add to my array. I am using the push method for a dynamic array 
      // as the number of objects returned by the observable is not static.
      this.rcs.getTalonPaie(ind.id)
        .subscribe( data => {
              this.listeTalonPaie.push(data.heures);
              test2.push(data.heures);
        });
     });
     // The output shows an empty list:
     // 1: 25
     // 2: 40
     // 3: 36
     // length: 4
     // __proto__ : Array(0)
     console.log('listeTalonPaie ', this.listeTalonPaie);
     // The output shows [null]
     console.log('listeTalonPaie ', JSON.stringify(this.listeTalonPaie));
     // The output is undefined
     console.log('Un element ', this.listeTalonPaie[0]);
     // The output is (3) [1, 2, 3]
     console.log('test ', test);
}

If you have a better approach to suggest, please let me know as I'm unsure if this is the correct way to achieve my goal.

Answer №1

When you push an array data into another array this.listeTalonPaie, you create a nested array [[1,2,3]].

If that was not your intention, consider using concat or spread syntax instead of push.

this.listeTalonPaie = [...this.listeTalonPaie, ...data.heures];

Noticing that my console.log() was returning undefined data.

Since the subscribe method is asynchronous, the console.log runs before the callback for data is executed. This example illustrates the scenario:

// mock subscribe implementation
const subscribe = (callback) => {
  // wait half a second then invoke callback with some data
  setTimeout(() => callback([1,2,3]), 500);
}

let result = [];

subscribe(data => {
  result = [...data];
  console.log('1:', result);
});

console.log('2:', result); // <-- called before 1

Answer №2

The issue lies in the subscription syntax. Creating a new function below with the necessary information and passing it to the subscription should resolve the problem.

this.rcs.getTalonPaie(ind.id)
    .subscribe( data => {
          this.listeTalonPaie.push(data.heures);
          this.logDataList(data)
    });
 });

logDataList(data: any) { console.log(data) };

If you can, retrieve data in ngOnInit so that accessing it in your onSubmit function becomes more straightforward.

Answer №3

Upon further investigation, I discovered that there wasn't an issue with my list functionality itself. It turns out that the console.log() was displaying undefined data instead of the expected values. Can anyone shed light on why this discrepancy is occurring?

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

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...

The length of JSONPath in Javascript is significantly longer, approximately 3000 times lengthier than a traditional loop

I am experiencing performance issues with JSONPath implemented in JavaScript using the Stephan Goessner Library. Below is an example of the JSON structure causing the problem: [ { id:1, name: "lorem", elements: [ ...

Exploring the getJSON function within jQuery

{ "Emily":{ "Math":"87", "Science":"91", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6f7e767c51767b727e737f764f747879">[email protected]</a>", "City":"Chicago" }, "Sa ...

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

Preventing Memory Leaks in Single Page Applications (SPAs) Using Google DFP with Angular and Vue: A Guide to Properly Destroying Ads and Their References

I recently encountered an issue while trying to implement Google's DFP in both Vue.js and Angular single-page applications (SPAs) where it appears to be leading to a memory leak. For Angular: I have created a proof of concept which can be found here. ...

The discovery of a commitment in the statement. The automation of unwrapping promises within Angular statements has been phased out

Struggling with errors while setting up a new AngularJS project. Here is the code for my app and controller; var app = angular.module('myApp', ['localytics.directives']) .config(['$parseProvider', function ($parseProvide ...

Is it possible to access a PHP variable from a different file in an HTML file?

Can someone help me with separating the javascript from this php file? I need to specify where the javascript should look for the php file, as currently it only executes within the php file. <?php date_default_timezone_set('Europe/London'); r ...

What is the best way to solve the Hackerrank Binary Tree problem using TypeScript and output the

Here is the coding challenge from Hackerrank: Given a pointer to the root of a binary tree, you are required to display the level order traversal of the tree. In level-order traversal, nodes are visited level by level from left to right. Implement the fun ...

I am having trouble getting the filter functionality to work in my specific situation with AngularJS

I inserted this code snippet within my <li> tag (line 5) but it displayed as blank. | filter: {tabs.tabId: currentTab} To view a demo of my app, visit http://jsfiddle.net/8Ub6n/8/ This is the HTML code: <ul ng-repeat="friend in user"> ...

The function database is not defined in firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default

Encountering an error message when attempting to connect my app to Firebase: firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.database is not a function After some testing, it seems the issue only arises when trying to connect to the database. The ...

The AJAX response doesn't seem to be halting

My AJAX request looks like this: $.ajax({ url: "AutoRFQ_Vendors_ST.aspx/BindVesselGrid", type: "POST", timeout: 3000, data: JSON.stringify(sendingdata), ...

Encountering an error in Angular 12 with DomSanitizer when setting the src attribute dynamically for an iframe. The issue arises when trying to set a

Having trouble creating a component to handle YouTube embedded videos? It seems like passing the src as a variable isn't working properly, no matter what is tried. Does anyone have any ideas on what might be going wrong, or if it's a bug in Angul ...

Highchart displays text centrally on legend hover

I am struggling with the code provided here. My goal is to make text appear in the center of the donut chart when hovering over the legend. Similar to how it works when hovering over a single piece of the donut chart. var chart = new Highcharts.Chart ...

The properties required by the type for typescript reactjs are not present

I've come across an array with the following structure: export const SideBarTags = [ { name: 'Tutorials', link: '../tutorials', icon: faFileAlt, dropdownItems: null, active: false, }, { name: 'An ...

When using AngularJS in conjunction with Karma-Jasmine, it is important to note that the functions verifyNoOutstandingExpectation() and verifyNoOutstandingRequest() may not

There is an unresolved HTTP request that needs to be flushed. When I use the following code afterEach(function(){ $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); The code functions correctly and I ...

Tips for running code extracted from a JSON payload

I have a JSON string that contains HTML and JavaScript code. I want to display this code on a page in my React app, but instead of just showing it as a string, I want the HTML and JavaScript to be executed as if it were hard coded. Currently, the code is ...

``JsViews and AngularJS: A Comparison"

I'm exploring the possibility of creating a single page application and came across jsViews/jsRender which seems very promising as it approaches Beta. As someone new to SPA development, I'm interested in understanding how jsViews stacks up agains ...

Guide on configuring the calendar to advance by one year from the chosen date in angular8 utilizing bootstrap datetimepicker

I am working with two calendars where the value of the second calendar is determined by the selection made on the first calendar. If the date selected on the first calendar is today's date, I want the second calendar date to start from one year after ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

Generate a configuration file that allows for the reading and storage of modifications

Is there a way to create a configuration file (JSON) on the local file system using JavaScript where I can write and modify data without losing it when the application is restarted? Any suggestions or solutions for this problem? Thank you for your assista ...