I'm having problems with variable scope in javascript. I have the following code that works fine except that the value of this.myUser becames undefined when it goes out of the .subscribe(...) block. I don't understand why since it's a class varibale. Here's my code:
private myUser: User;
      login(username: string, password: string): User {
          this.http.get(this.loginUrl + '?username=' + username + '&password=' + password)
            .map((response : Response) => response.json())
            .subscribe(data => {
                console.log('data inside', data);
                this.myUser = data;
                console.log('user inside', this.myUser);
              }
            );
          console.log('user outside', this.myUser);
          return this.myUser;
      }
And here's the result from console log:

I'm using angular 4 with bootstrap 4 (but I don't think that has any influence on the issue).
Thanks for any hint.
Edit
I red the link below, so I tried to add promise to my code to manage async calls. Online tutorials seems all very simple (too simple indeed, included the Angular official reference), so I ended up with something like this:
this.http.get(this.loginUrl + '?username=' + username + '&password=' + password)
      .toPromise()
      .then(data => {
            console.log('data inside', data);
            this.myUser = data.json() as User;
            console.log('user inside', this.myUser);
          })
      .catch(console.log.bind('Error!'));
But it doesn't have any effect on the application flow. I'll keep trying, but any help will be appreciated.
 
     
    