0

I am making a simple angular application trying to learn angular. I am using an online api from json placeholder for backend which stores my login credentials. I am retrieving these using an http.get request. When I login for the first time the http request returns undefined but the second time it returns the correct credentials. I am confused at this behavior

My login function:

loginUser(email: string, password: string)
 { 
  this.data.getCreds().subscribe(data => {

  this.mail = data.credentials[0].email;                 
  this.pass = data.credentials[0].password;              
 });

 console.log(this.mail,email,this.pass,password, 'here!!!');

 if(this.mail==email&&this.pass==password)
  {
   this.isLoggedIn = true;
   localStorage.setItem('loggedIn', 'true');
   this.router.navigate(['/admin']);
  }

}

My getCreds function from the data service:

     getCreds(): Observable<any>{ return this.http.get("https://my-json-server.typicode.com/divyanshu-avi/login/db").pipe(map(data => data));
    }
  • 5
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – Vikas Jun 18 '19 at 11:12

3 Answers3

0

You won't get the data synchronous, the code in the subscribe block is triggered asynchronously as soon as the data are returned from the service. In other words, it is expected that after subscribe, both mail and pass are not initialized.

Ronald Korze
  • 734
  • 5
  • 16
0

This behaviour happens because the console.log is outside the subscribe function. Subscribe is asynchronous, meaning that your console.log might run before the getCreds response are obtained. What you should do to fix it is to put the console.log inside the subscribe function, like the code below:

loginUser(email: string, password: string)
 { 
  this.data.getCreds().subscribe(data => {

  this.mail = data.credentials[0].email;                 
  this.pass = data.credentials[0].password;              
  console.log(this.mail,email,this.pass,password, 'here!!!');
 });

 if(this.mail==email&&this.pass==password)
  {
   this.isLoggedIn = true;
   localStorage.setItem('loggedIn', 'true');
   this.router.navigate(['/admin']);
  }
}

the second time you run the login method worked because the var mail and pas still had the value from the first run.

mvoelcker
  • 330
  • 4
  • 8
0

Remove map no need at all of you application

 getCreds(): Observable<any>{ return this.http.get("https://my-json-  server.typicode.com/divyanshu-avi/login/db");

You can use setTimeout() for subscribe the observable

Md Rana Hossain
  • 304
  • 2
  • 7