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.