0

I have made an API to display the followers and following users of an user. Everything is displayed properly on the screen. But the problem is if I try to console.log() the array it is stored in after calling the method it says that it is an empty array. I'm really stuck and don't know what to do further. Here are my examples could someone help out or is experiencing the same problem please let me know.

ngOnInit:

ngOnInit(): void {
    localStorage.setItem("gd", "78F88FC0-7A58-49CD-881E-4B36C5C29B71");
    this.getUsers();
    this.getFollowing();
    this.getFollowers();

    console.log("Followers: ", this.followers)
    console.log("Following: ", this.following)
}

Methods:

getUsers() {
    this._userService.getUsers().subscribe(res => {
      this.users = res;
    })
  }

  getFollowing() {
    this._userService.getFollowing().subscribe(res => {
      this.following = res;
    })
  }

  getFollowers() {
    this._userService.getFollowers().subscribe(res => {
      this.followers = res;
    })
  }

Console:
enter image description here

HTML output:
enter image description here

AntonioSk
  • 528
  • 3
  • 20
  • 2
    [console.log is not synchronous](https://stackoverflow.com/a/23392650/740553). Unless you deep-copy your object before logging it, you _cannot use it_ for determining what data looks like at what point in your code: use breakpoints in the debugger, instead. – Mike 'Pomax' Kamermans Oct 19 '20 at 22:00
  • 1
    None of your code is showing where you're doing a `console.log` that doesn't have the expected results. Also, you should post the real code, not screenshots of code. – Jacob Oct 19 '20 at 22:00
  • I have updated it – AntonioSk Oct 19 '20 at 22:03
  • 5
    Your calls are all async. Put your consoles inside your subscribe’s. – MikeOne Oct 19 '20 at 22:06
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Oct 19 '20 at 22:24
  • Thanks for the tips it works right now thanks y'all – AntonioSk Oct 20 '20 at 06:31

1 Answers1

0

I want to make an answer less generally that the link exposed

We can use forkJoin to make all the calls and get the response in an unique subscribe

ngOnInit()
{
    forkJoin(this._userService.getUsers(),
             this._userService.getFollowing(),
             this._userService.getFollowers())
             .subscribe(([users,following,followers])=>{
                   this.users=users
                   this.following=following
                   this.followers=followers
                   console.log(this.users) //<---give value
             })
             console.log(this.users) //<--has no value outside subscribe function
}

And yes, only has sense into subscribe function make a console.log(this.users)

Remember: the services return observables, we subscribe in components

Eliseo
  • 50,109
  • 4
  • 29
  • 67