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

What is the process for invoking an Express route using Ajax?

I encountered a problem with calling an Express route in my Node.js application using Ajax when submitting a form. Here is the code for my route: router.post("/user", function(req, res) { console.log("FORM DATA: " + JSON.stringify(req.body)); res ...

Using *ngIf to verify the presence of an attribute

Currently working with Angular2 and trying to implement a condition to display something. For instance, if group.permissions=Can Create File, then something should appear on the page. This is the code I have written so far: <div class="col-md-9" *ngI ...

Creating a web form with the ability to select multiple images using Javascript

Currently, I am in the process of developing an HTML form that enables users to select an image, a URL, and text that will be inserted as a <li> into a webpage. However, I am facing an issue where I want users to create multiple <li> per input. ...

The appearance of the Angular app undergoes a change following deployment using ng build

I have been working with Angular for several years now, but only recently delved into using Angular Material components in my latest project. I was pleased with how my layout turned out and ready to push it to production. However, after deployment, the com ...

Display notification if the request exceeds the expected duration

Is there a way to display a message when a request is taking too long? For instance, if the request exceeds 10 seconds in duration, I want to show a message asking the user to wait until it finishes. fetchData(url, requestParams) { return this.restServic ...

Updating the value of the variable using ng-submit

My application displays Quantity: {{num}}. The default value is set to 3 in the scope. The objective is to click on: <form ng-submit="addContact()"> <input class="btn-primary" type="submit" value="Add Contact"> </form> and to up ...

The JSX component cannot be named 'Stack.Navigator' or used as such

Encountering a type issue with react navigation using Stack.Navigation or Stack.Group from createNativeStackNavigator The error message indicates that the types do not match with JSX.element. Specifically, it states: Type '{}' is not assignable ...

Issue with Angular 2+ removeAt method not functioning properly within a nested component

Currently, I am utilizing model-driven approach for the form in angular4. I have passed a formarray to the child component using @input. However, whenever I try to use removeAt function on it, it throws an error: removeAt is not a function This is wha ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

Obtain the Zero-width non-joiner character (‌) using the innerHTML attribute

I am attempting to retrieve a &zwnj; using the innerHTML method The desired output should be This section contains a zero-width‌&zwnj;non-joiner, a non-breaking&nbsp;space &amp; an ampersand However, the current output is: This part c ...

What Google Domain Verification APIs are needed for verifying domains in Pub/Sub?

I've written this code that utilizes a Domain token to verify a domain with Google using the Site Verification API: const auth = await this.gcp.getApplicationCredential(accountId, projectId,[ 'https://www.googleapis.com/auth/siteverification ...

We were unable to load the resource because the server returned a 404 (Not Found) error. The EnterpriseMaster/BindNatureofAssignment feature is not functioning properly after being published

While the code is working perfectly fine on localhost, as soon as I publish it I encounter an error that prevents the table from loading. EnterpriseMaster/BindNatureofAssignment:1 Failed to load resource: the server responded with a status of 404 (Not ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

Why am I encountering a 400 error with my mutation in Apollo Client, when I have no issues running it in Playground?

After successfully testing a mutation in the playground, I attempted to implement it in my Apollo client on React. However, I encountered an error message stating: Unhandled Rejection (Error): Network error: Response not successful: Received status code 40 ...

Adjusting the visibility of a div as you scroll

I'm trying to achieve a fade-in and fade-out effect on div elements when scrolling over them by adjusting their opacity. However, I'm facing difficulties in getting it to work properly. The issue lies in the fact that my div elements are positio ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

A combination of Tor Browser, Selenium, and Javascript for

I have been attempting to use selenium with Tor, but unfortunately it is not functioning correctly. I have come across a library that allows for this functionality, however, it appears to only work with Python. Is there a way to accomplish this using Jav ...

Discover the best way to integrate your checkbox with your Jquery capabilities!

I am having trouble getting my 3 checkboxes to interact with the JQuery button I created. The goal is for the user to be able to select an option, and when the button is clicked, the selected options should download as a CSV file from my feeds. Below is th ...

Displaying selected values in a Multi Select Listbox upon submission of the same form when an error occurs

When the page is first loaded: Retrieve the values from the table field and store them in a variable If the field is blank, do not take any action Populate the listbox with default custom values When the form is submitted (on the same page) and multipl ...