Encountering an error of "undefined" when attempting to access loop variables within the ngOnInit() lifecycle hook

When I call the ngOnInit() function, data is fetched from a service and stored for use in my component. However, I am encountering issues with accessing this data outside of the subscribe method. I am unsure of what the problem might be.

import { Component, OnInit, Renderer2, HostListener,ViewChild, TemplateRef, Inject} from '@angular/core';
    import { DOCUMENT } from '@angular/common';
    import { NgbModalOptions, NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-pattern',
  templateUrl: './pattern.component.html',
  styleUrls: ['./pattern.component.scss']
})

export class PatternComponent implements OnInit {


  public config: any = {};

  constructor(@Inject(DOCUMENT) private document: any,private modal: NgbModal,private pattern:patternService) { }

  ngOnInit(): void {

   this.pattern.Pattern(this.local).subscribe(
      data => {

      for (var i = 0; i < this.length1; i++){
         this.visitedArray[temp1] = [false, this.Patternarray[i]]; //I'm trying to access this in onselect() function. If the value is false I'm trying to do something
         console.log("Visited Array ng:",this.visitedArray[temp1]);
        }
       },
      err => {
        console.error(err);
      }
    );
 }
}

Within my onselect() function, I attempt to retrieve the data stored in this.visitedArray[this.temp1] from the ngOnInit method. Unfortunately, I am unable to access it successfully and the console displays 'Visited Array:' as undefined.

onselect(row, i) {

      console.log("Visited Array:",this.visitedArray[this.temp1]);
       console.log("visited id:",this.visitedArray[this.temp1][0]);

    }

Answer №1

When calling the service asynchronously, the code outside of the subscribe function will run first. The code inside the subscribe function only executes once the service returns data, which could take some time. This means that you may be trying to access a variable before it has been assigned a value (i.e. within the subscribe function), resulting in an undefined error.

To resolve this issue, make sure to process your data once it has arrived (i.e. within the subscribe function).

Answer №2

To put it simply, follow these steps:

this.pattern.Pattern(this.local).subscribe(
      data => {
      this.length1 = this.patterns.length;
      this.visited_count=this.length1-1;
     for (var i = 0; i < this.length1; i++) {
          this.Patternarray[i] = this.questions[i].Id;}
     for (var i = 0; i < this.length1; i++){
         this.visitedArray[temp1] = [false, this.Patternarray[i]]; //When accessing this in onselect() function, if the value is false, do something
         console.log("Visited Array ng:",this.visitedArray[temp1]);
        }
onselect(row,i); // Call onselect from this point
       },
      err => {
        console.error(err);
      }
    );

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

Encountering a problem with ng serve while attempting to launch the project

I am completely new to Angular and recently installed the latest version of Node.js along with Angular CLI globally. I cloned a project from GitHub and attempted to run it using 'ng serve', but encountered an error message: https://i.sstatic.net ...

Are there any other options for handling the click event for all elements in Angular besides writing a click function for

click here for code screenshots https://i.sstatic.net/3EHOU.png see more code screenshots here https://i.sstatic.net/CcFZq.png This image displays five(5) li elements, each with the same function. However, if there are many more li elements, I am intere ...

Mastering the Art of Mocking ControlContainer in Angular Unit Testing

Is there a way to simulate a ControlContainer instance in order to effectively test my component? One of my child components incorporates a ControlContainer within the constructor, leading to usage like this: <acr-score-card formGroupName="score">& ...

Challenges with formArrayName in Angular can be tricky to navigate

I am in the process of developing an Angular library with the main feature being the provision of a selector with two inputs: a reactive form containing the data an object literal specifying which properties of the data should have editable input fields ...

Setting up Typescript: The Guide to Declaring a Dependent Property

In my current project, I am working on creating a declaration file for the quadstore library. This library has a class that requires a constructor parameter called contextKey. The value of this parameter determines the name of a field on method arguments. ...

"Enhancing security measures from the back-end API to the front-end framework

My team is currently evaluating different Javascript Frameworks (Vue/React/Angular) to determine which one best fits our company's needs. Our objective is as follows: Backend API(C#) -> Framework(Vue/React/Angular) In order to protect our data f ...

Showing the chosen dropdown option using formControlName in ReactiveForms

I have a dropdown menu with validation using formControlName. I also wanted to display the selected option from the dropdown. To achieve this, I used ngModel. However, I encountered an error message stating: It seems that you are using ngModel on the same ...

How can I properly integrate md5 hash in an Angular 2 typescript file?

Struggling with implementing md5 hash for user passwords in Angular 2. Despite importing the Md5 module in my typescript file, it doesn't seem to be recognized when I run the application. https://i.sstatic.net/dxtd2.png Even though Visual Studio reco ...

Passing an identification number to a function when clicking a button within an Angular Material table

In my Material Table displayed here: https://i.sstatic.net/zO2aS.png The code for the "Action" column is shown below: <ng-container matColumnDef="Action"> <th mat-header-cell *matHeaderCellDef> Action</th> <td mat-c ...

Utilizing Partial Types in TypeScript Getter and Setter Functions

Within the Angular framework, I have implemented a component input that allows for setting options, specifically of type IOptions. The setter function does not require complete options as it will be merged with default options. Therefore, it is typed as Pa ...

Saving the compiled Angular dist folder in the artifactory repository

Our team utilizes Artifactory to manage libraries and artifacts. We have configured the npm registry to point to our Artifactory URL for library retrieval. GitLab is integrated into our CI pipeline. Specifically, I have implemented a job that compiles the ...

Having trouble getting this multi-select feature to function properly in Reactjs with Typescript? Let's figure out the solution together

I encountered an issue where I was unable to select multiple items due to a join error code "Property 'join' does not exist on type 'unknown'." in a .tsx file const DropdownMultiselect =()=> { return( <> ...

Configuring modules using Sass, CSS-Modules, Webpack, React, and TypeScript

I'm facing an issue with extracting types from my .scss files. I've tried various configurations and solutions, but nothing seems to work. Specifically, my goal is to utilize modules in a React app with TypeScript. Below is my webpack configura ...

Make sure the static variable is set up prior to injecting the provider

In our Angular6 application, we utilize a globalcontextServiceFactory to initialize the application before rendering views. This process involves subscribing to get configuration from a back-end endpoint and then using forkJoin to retrieve environment app ...

Diving deeper: Angular and NPM dependencies compared to devDependencies

After doing a lot of reading on this topic and following this very informative post at: What is the distinction between dependencies, devDependencies, and peerDependencies in an npm package.json file? I have learned that dependencies should include all ru ...

What steps are necessary for TypeScript to retrieve my definitions when utilizing node.js require statements?

I have been utilizing Visual Studio 2013 tools for Node.js along with VS2013 Update 2. In my util.ts file, I have the following code: var Util = function () { this.getSelectOption = function (elem, value) { var x = 99; } module.exports = ...

`Typescript does not adhere to the specified type when used inside a for loop with a local

This code snippet declares a variable venuelist of type Venue array and initializes it as an empty array. The type Venue has a property named neighborhood. There is a for loop that iterates through the venuelist array and checks if the neighborhoods matc ...

Navigate to a specific route on Angular 5 with varying parameters

Can someone help me with navigating to the same route with different parameters? Currently, when I try to do this, it redirects me to a different route. However, if I press the back button, it takes me to the correct page. Any suggestions? Here are my rou ...

Resolving problem in React component: TypeScript error - Unable to find property 'type' on 'string' type

In my React typescript component, I have defined a custom block that filters and displays data: type CustomTeaser = Exclude<Teaser, TeaserThree>; const MyCustomBlock = ({ customItems }: Props) => { const sixGridData = { items: customItems as Cu ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...