Package.JSON
Package.JSON

Reputation: 301

angular: wait for asynchronous data

I am using Angular and trying to validate the user credentials for a login page in my service.ts file by sending the request to a backend. I want to wait for the server response in my component.ts file but, I am unable to do so.

Here's my code:

Service.ts

check_authentication(mail: string, passcode: string)
{
  const params = new HttpParams().set('id', mail).set('id2', passcode);

  this.http.post('http://localhost:3000/login', this.test, {params, responseType: "text"})
  .subscribe(responseData => {
    if(responseData == 'Authorized')
    {
        this.check = true;

    }
    else
    {
        this.check = false;

    }
  }
  ,error => {
    console.log("Error occurred while trying to login "+ error.message);
  });
}

isAuthenticated() : boolean
{
  return this.check;
}

Component.ts

onSubmit()
{
  
  this.auth.check_authentication(this.mail, this.code);

  //this if-else block isn't executing as somehow the response from the server isn't there yet.
  //I want to wait for the response here
  if(this.auth.isAuthenticated() == true)
  {
    console.log("submit button called here");

    this.router.navigateByUrl('/home');
  }
   
  else if(this.auth.isAuthenticated() == false)
  {
    this.unAuthorized = true; //as I am throwing an alert if user login fails
  }

   console.log("Printing this to see if this function is being called correctly"); //this executes 
}

Any help would be appreciated.

Upvotes: 0

Views: 202

Answers (1)

John
John

Reputation: 11399

The check_authenticationl is asynchronous, meaning that the value is not ready before you check if the user is authenticated or not. There are several approaches to solve this. One is to let check_authentication return a Promise.

In the service:

    check_authentication(mail: string, passcode: string)
    {
      const params = new HttpParams().set('id', mail).set('id2', passcode);
      return new Promise((resolve, reject) => { // create a promise that resolves after the api returns a response

      this.http.post('http://localhost:3000/login', this.test, {params, responseType: "text"})
      .subscribe(responseData => {
        if(responseData == 'Authorized') {
            resolve(true);
        } else {
            resolve(false);
        }
      }, error => {
        console.log("Error occurred while trying to login "+ error.message);
        reject();
      });
    })
      
    }

In the Component

    this.auth.check_authentication(this.mail, this.code).then( isAuth => {
      if(isAuth){

      }else{

      }
    });

Upvotes: 2

Related Questions