Vanshita Khatri
Vanshita Khatri

Reputation: 33

Angular 9: Object getting udefined in ngOinit even after assignment

I am trying to access an object which is assigned by function in ngOnInit, but console log showing it undefined, whereas the same variable is accessible inside 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 clueless about it, please help.

Upvotes: 0

Views: 160

Answers (1)

Ben Ari Kutai
Ben Ari Kutai

Reputation: 569

It is a classic race condition problem.

LoadCompanyInfo() returns an observable which is asynchronous, and therefor

console.log(this.selfcompanies);

occurs before the assignment.

this.selfcompanies = data;

Upvotes: 1

Related Questions