TypeError: Cannot read property 'firstName' of undefined in ionic

Viewed 344

I created a function that returns Promise

ject 

i can access the response's data inside the scoop of the 'then' accessor and read it's value there, but outside the data is not being attributed to the 'User' object so it's returning this error : 
>Uncaught (in promise): TypeError: Cannot read property 'firstName' of undefined

1 Answers

The problem is because your console.log is out of then function.

Because the function then wait for the response, when you put out of the function, Angular will continue the process

If you want to access this form, you can write the code like this:

async ngOnInit(){
  try{
    const value =    await this.userService.getCurrentUser()
    this.user.firstName = value['data']['first_name'];
    console.log(this.user.firstName);
  }catch(error){
    console.log(error)
  }
}

Related