Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined

Please refer to the image for a visual representation of my problem.

I'm not sure what I might be overlooking, so any help would be greatly appreciated.

The array in question is named nameTable and consists of strings.

  1. Upon executing console.log(this.nameTable), the output shown can be viewed in the attached image.

Link to Image Description

Additionally, upon further investigation by clicking the arrow, the result depicted in the second image was observed:

Link to Image Description

The main challenge arises when attempting to display the 5 elements within the table using a for loop.

for (let i = 0; i < 5; i++){
        console.log(this.nameTable[i])
        }

Despite the intended logic, as showcased in the provided image, the output returned happens to be undefined.

Link to Image Description

Given below is a snippet of the code highlighting the relevant section:

// Relevant Code Section
employeeL:Array<Awinjard> = [];
inv_agentTab: Array<Inv_agent> = [];
drafbiesTab: Array<Drafbies> = [];
// Additional Declarations
// Initialization in ngOnInit Method
nameTable:Array<string> = [];

ngOnInit() {
    this.folder = this.activatedRoute.snapshot.paramMap.get('id');
  
    this.awinjard.getAwinjardMatricule().subscribe(res => {
      // Further Implementation Logic
    })
}

Answer №1

After subscribing to the getAwinjardNameAr method, you may encounter an issue when trying to access the nameTable array before receiving a response, resulting in the value being undefined. While @raishav-hanspal has provided a solution that works, making a small code adjustment can simplify things. I recommend placing the code within your for loop inside the subscribe function. See the modified code snippet below:

this.awinjard.getAwinjardNameAr().subscribe(res2 => {
          this.drafbiesTab = res2 as Array<Drafbies>
      this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
          this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
          this.nameTable.push(this.nameemployee);
          let awin= <Awinjard> {
          matricule: this.matriculeTable[this.inv_agentNombre],
          fullname: this.nameemployee,
          status: true,
          done: 1,
          mustBeDone:40
        }
        this.employeeL.push(awin);
        })

Answer №2

To improve efficiency, consider moving the code that logs nameTable[] inside the subscribe function where values are being pushed into nameTable[].

For a comprehensive solution, utilize complete within subscribe() -->

this.awinjard.getAwinjardNameAr().subscribe(res2 => {
          this.drafbiesTab = res2 as Array<Drafbies>
          this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
          this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
          
          this.nameTable.push(this.nameemployee);
        
        },err => {console.log(err)}, ()=> {
      for (let i = 0; i < 5; i++){
      // The issue lies in accessing data from the nameTable array here
        console.log(this.nameTable[i])}})
      });
      

More information can be found at https://angular.io/guide/observables

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

Incorporating lodash into Angularjs for enhanced functionality

After stumbling upon an app online that utilizes AngularJS with Lodash, I noticed a simple way in which Lodash is incorporated. By including the following line in the body (after angular has been included): <script src='vendor/lodash/3.3.1/lodash. ...

Sending data to the server using the $.post method with an

I am having some trouble creating a post using a customized model: public class CallbackPriorityItemModel { public int userID { get; set; } public int order { get; set; } public string name { get; set; } } Unfortunately, I can't seem to ...

iterating through the checked values in Angular 4

I need assistance in writing a loop using TypeScript to send each checked employee as a parameter to the postCouncilAbsence function. Can anyone help? component.ts: onattendanceSave(form:NgForm){ this.index = this.attendanceForm.value console.log ...

What is the best approach to developing Vue components with unique templates while maintaining the same functionality without duplicating code?

I am working on a project to develop a custom and versatile datatable component. My goal is to be able to adjust the appearance of the datatable on each page, while maintaining consistent functionality. I want to pass data rows into the component and have ...

Executing the command `npm run jshint` yields the error message `script not found: jshint`

Currently, I'm attempting to run jshint on a few javascript files. However, I am encountering an issue where the local npm install of jshint is not functioning as expected. Upon checking, the package is indeed present: $ npm list --depth=0 <a hre ...

Using the class attribute for Pagedown instead of the id keyword

I am utilizing Pagedown, which necessitates giving the id wmd-input to a textarea. This requirement is outlined in Markdown.Editor.js as follows: function PanelCollection(postfix) { this.buttonBar = doc.getElementById("wmd-button-bar" + postfix); ...

When interacting with a <select> element, the behavior of test script execution varies between Firefox and Chrome

I've encountered an unusual problem that I need help describing and solving. Your assistance is greatly appreciated! The issue I'm facing involves Testcafe behaving differently when running the same test script on various browsers. testcafe: ...

Tips for positioning divs on top of an image with Twitter Bootstrap

I'm having an issue with displaying an image and dividing it using bootstrap div columns. The problem is that the image is overlapping the divs, making it impossible to click or attach jQuery events to it. Here is the code I am currently using: #view ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Utilizing *ngfor in Angular 7 to Group and Display Data

I currently have incoming data structured like this in my Angular application Visit this link to see the data format https://i.stack.imgur.com/jgEIw.png What is the best way to group and sort the data by State and County, and present it in a table as sh ...

The service worker is attempting to access outdated information from the cached script

Within my project, I implement the loading of JSON files asynchronously using import().then. At times, a situation arises where new content is accessible but has not yet been applied, causing the old cached script bundle to attempt loading the JSON files ...

How to modify the background color in Material Ui's datepicker?

Is there a way to customize the background color of my Material UI datepicker modal? To change the colors, you can use the createMuiTheme function from "@material-ui/core": const materialTheme = createMuiTheme({ overrides: { MuiPickersToolbar: ...

Obtaining JSON data in React Native without prior knowledge of the key

When I receive this type of data, the keys are common but the items vary. How can I extract and add this data to my list of categories? { "99": "Venues", "100": "Party Supplies", "101": "Enter ...

Pass an array containing an HTML string to the $.post method in jQuery

I have a problem with displaying HTML content fetched from a PHP script using the jQuery $.post method: $.post('{$site_url}tests/tests/content', params, function (data) { $('#some-div1').html(data[1]); $('#some-div2').htm ...

Tips for resolving issues with storing data in a text box that is constantly being added to

Can someone please assist me with this issue I'm facing? I am using isset to check if the index is defined, but it stores 0 instead of saving the value of the textbox. How should I tackle this problem? If I don't check if the index is defined and ...

Utilizing jQuery in Wordpress to Toggle Content Visibility

Currently, my website pulls the 12 most recent posts from a specific category and displays them as links with the post thumbnail image as the link image. To see an example in action, visit What I am aiming to achieve is to enhance the functionality of my ...

Switching images through onmouseover, onmouseout, and onclick interactions

I have two images named img1 and img2. Here is my code: function roll(id, img_name, event_name, img_id) { var state ; if(event_name == 'mouseover') { state = false;rollover();} else if(event_name == 'mouseout') { ...

Support for Vue 3.4 same-name shorthand has been added to VS Code

After upgrading my Vue 3 project to version 3.4, I encountered an issue with vs-code highlighting same-name shorthand as an error, even though it was functioning correctly in my code. I am using the volar extension. Is there a way to resolve this so that v ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...