Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
Why is the component property undefined when called in another function?

I am working on an Angular project where I am authenticating my user and I want to get the current authenticated user which works fine. I set the component user property in NgOnInit() but then I try to access the property in another function and it undefined there even though I have assigned it a value of the authenticated user. Why is that and how do I prevent it from happening?

Here is my code:

NgOnInit()  {
   this.setCurrentUser();
   this.getData();
}



  setCurrentUser() {
     Auth.currentAuthenticatedUser().then(user=> {
      console.log(user);
      this.currentUser = user;
    })
  }

   getData = () => {
    console.log("DATA USER:")
    console.log(this.user)
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It is happening because of aync function Auth.currentAuthenticatedUser(). you can use async...await or call the getData() in then()
then approach

    setCurrentUser() {
     Auth.currentAuthenticatedUser().then(user=> {
      console.log(user);
      this.currentUser = user;
      this.getData();
    })
  }

Async...await approach

async NgOnInit()  {
   await this.setCurrentUser();
   this.getData();
}

  setCurrentUser() {
     return Auth.currentAuthenticatedUser().then(user=> {
      console.log(user);
      this.currentUser = user;
    })
  }

   getData = () => {
    console.log("DATA USER:")
    console.log(this.user)
  }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!