Home > Blockchain >  Can't access api response outside of its method
Can't access api response outside of its method

Time:11-21

I'm trying to fetch a list of users from a backend API. It all works perfectly unless that once I log the getAllUsers() method in the ngOnInit I get the data, but when I log the variable containing the list of users I get undefined.

Here is my code:

users:User[];

  constructor(private userService:UserService) { }

  ngOnInit(): void {
   this.getAllUsers(); 
   console.log(this.users); // ==> shows undefined
    
  }

  getAllUsers() {
    this.userService.getAll().subscribe({
      next:(data) => {
        console.log(data); // ==> shows the result
        this.users=data
      }
    })
  }

Can anyone explain the difference between them? And how can I access the response outside the subscribe method? I'm still new to angular though! thanks in advance!

CodePudding user response:

The fetch from backend api is an asynchronous call, which means iydk takes time to load. That's the reason why the console.log in ngOninit shows undefined and the function doesn't. I hope it answered your question

CodePudding user response:

Within getAllUsers you do an asynchronous request. next is executed once the request is done and yields the result. However within ngOnInit you do the console log directly after starting the call. At this point the request is not done yet and didn't assign the data yet.

  • Related