0

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.

1 Answer 1

2

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{

      }
    });
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. I was trying to use the promise but, seems like I was running into syntax error. :)
I haven't tested the code I wrote, so there might be some syntax errors there :S

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.