-2

I tried to send an HttpRequest in Typescript. I need to store the recieved data outside of the subscribe function. But when I want to print the user variable outside of the subscribe, it is undefined. In the subscribe function it works fine. So how I can get access to the data outside of the subcribe function?

private user: User;

public sendHttpLogin(username: string, password: string) {

  this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
    //save the data on a User Object
    this.user = data;
    //this works fine
    console.log(this.user)
  });

  //this is undefined
  console.log(this.user);
}
Moritz
  • 139
  • 1
  • 10
  • 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) – CertainPerformance Apr 22 '20 at 11:33

1 Answers1

0

The second console.log gets called before the http.get has returned anything, so that's why it's undefined.

Your first console.log is correct, you can only use the data once it has returned from the get function.

You could call another function there to continue the flow of your application.

private user: User;

public sendHttpLogin(username: string, password: string) {

  this.http.get<User>('http://localhost:8080/login?password='+password+'&username='+username).subscribe(data => {
    this.continueApp(data)
  })
}

private continueApp(data){
    this.user = data
}
Kokodoko
  • 26,167
  • 33
  • 120
  • 197