Error in Angular 9: Object remains undefined in ngOnInit despite being assigned

When trying to access an object assigned by a function in ngOnInit, I am encountering an issue where the console log is showing it as undefined. Oddly enough, the same variable is accessible inside the LoadSelCompanies subscription block:

export class dealComponent implements OnInit {
  selfcompanies;
  self;
  dealForm: FormGroup;
  constructor(private userService: UserService) { }
  ngOnInit() {
    this.AddControls();
    this.LoadSelCompanies();
    console.log(this.selfcompanies);
  }

  LoadSelCompanies() {
    this.userService.LoadCompanyInfo().subscribe(data => {
      this.selfcompanies = data;
      console.log(data);
      console.log(this.selfcompanies);
    });
  }

I am currently at a loss and seeking guidance on this matter.

Answer №1

This issue stems from a common race condition scenario.

The function LoadCompanyInfo() produces an observable that operates asynchronously, resulting in

console.log(this.selfcompanies);

being executed before the actual data assignment takes place.

this.selfcompanies = data;

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

Enhance your Angular material datepicker with additional content such as a close button

I'm currently working on customizing my Angular Material datepicker by adding a button. The goal is to have this button placed in the top right corner and enable it to close the datepicker when clicked. In addition, I also want to include extra conte ...

Discovering the true rendering elements in karma tests: A guide

Recently, I started working on a new project in Angular14. However, when I completed writing the unit tests, all I could see was a series of successful text information and not any HTML elements displayed. How can I view the HTML elements? ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...

React/Ionic: Avoiding SVG rendering using <img/> elements

I seem to be encountering an issue when trying to load SVG's in my React/Ionic App. I am fetching weather data from OpenWeatherMap and using the weather?.weather[0].icon property to determine which icon to display. I am utilizing icons from the follow ...

Developing J2EE servlets with Angular for HTTP POST requests

I've exhausted my search on Google and tried numerous PHP workarounds to no avail. My issue lies in attempting to send POST parameters to a j2ee servlet, as the parameters are not being received at the servlet. Strangely though, I can successfully rec ...

What is the best way to position the arrow next to the header of a sorted table?

I've been working with a table and wanted to enable sorting on all table headers, so I decided to refer to the bootstrap example for guidance. The issue I encountered in this example is that the arrow indicating sort direction appears on the left sid ...

Angular 6's removeAt and trackBy functions are causing issues in updating the formArray and not reflecting the

Within a formGroup, I am adding and deleting elements from a formArray. To keep track of the ids to delete, I am using trackBy. When calling the function delete(i), it successfully removes the correct element from the formArray in the form. However, in th ...

Angular dependency issue: Expected '{' or ';' for @types/node

I encountered an error while running "ng serve" in my Angular application. Originally built as Angular 2, it was upgraded to Angular 8 (with attempts at versions 6 and 7 along the way). However, after migrating from Angular 5, I started experiencing errors ...

Executing a service call within an Angular 2 structural directive

I've developed a custom structural directive to verify a user's permissions. The permissions are retrieved from the backend and stored in the service itself. The directive utilizes dependency injection to access the service and determine if a spe ...

Why doesn't package.json typically utilize the preset values stored in the .npmrc file?

Windows 10 x64 Based on the information found here, I created a file called C:\Users\bushm\.npmrc with the following content: author = "Andrey Bushman" However, when I run the command npm init -y in a new directory, I noticed that the pac ...

Discovering a DOM Element Post Mouse Click Event Using HostListener in Angular 8

Is there a way to locate the current DOM element on a page after clicking the mouse? I am currently attempting to utilize HostListener in Angular 8. @HostListener('click') onClick(){ window.alert('Current DOM element is'); } ...

Guide on inputting Vue component in props

<template> <v-dialog width="auto" v-model="isShown" transition="dialog-bottom-transition" > <v-card> <v-card-title v-if="title"> {{ title }}</v-card-title> ...

Breaking down an object using symbols as keys in Typescript

I'm encountering an error when running this code Type 'symbol' cannot be used to index type '{ [x: string]: string; }'.: let symbol = Symbol() let obj = { [symbol] : 'value'} let { [symbol]: alias } = obj // ...

Updating the FormControl value using the ControlValueAccessor

I have developed a directive specifically for case manipulation. The code I created successfully updates the visual value using _Renderer2, but I am facing an issue with formGroup.value. Even though the directive visually changes the value as expected, t ...

Exploring intricate JSON data in Angular 4 applications

Below is the json structure I have: [ { "section":{ "secName":"Module 1", "pages":[ { "pageName":"Page 1", "pageType":"brightcove", "pageData":[ { ...

Error message: Failure to define class methods when exporting the class from a file

In my project, I have defined a class called BinarySearchTree in a file named a.js. This class has been exported and then imported into another file where it is used as the parent class for a different class called Traversal. However, I encountered an issu ...

An unusual situation occurs in Angular 2 when using Zone.js and CommonJS modules: the code within an IF statement is executed even when the condition

After numerous checks, I have come across a peculiar anomaly. Within my Angular 2 service, I am loading a @type definition (typescript 2) that in turn loads a commmon.js module (visionmedia/debug). Inside this common.js module, there is a simple if stateme ...

Troubleshooting: Vue and TypeScript Components Not Communicating

Vue is still fairly new to me and I'm struggling with this issue. Despite following code examples, my implementation doesn't seem to be working correctly. The component I defined looks like this: <template> <div class="row"> ...

The data does not have a property named 'formData' according to the type 'Event'

Encountered an issue while attempting to compile my TypeScript code: typescript Property 'formData' does not exist on type 'Event'? formElem.addEventListener("submit", (e) => { // prevent default action on form submiss ...

Angular integration with MSAL incorporating unprotected resources

Integrating Azure AD into my Angular app has been going smoothly, except for one issue with how it handles HTTP requests. To address this, I added a standard http interceptor to the app: { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, mult ...