I have a button that when I click it, it logs the user into the database via an API call however the code doesn't seem to wait for the response until the second click of the button.
HTML:
<button class="login-button" [disabled]='!loginForm.valid' (click)="login()">Login User</button>
Login.Component.ts:
login() {
this.getLoginDetails();
// After the first click of the button this is 'undefined' but after the second it returns the details
var details = this.loginResponse;
// Store details in session
localStorage.setItem('token', details.token); // Throws exception on first click due to 'details' being undefined
localStorage.setItem('refreshToken', details.refreshToken);
localStorage.setItem('userId', details.userId.toString());
this.router.navigate(['/subscribers']);
}
getLoginDetails(){
var data = JSON.stringify({
"EmailAddress": this.loginForm.controls['userName'].value,
"Password": this.loginForm.controls['password'].value
});
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
// After the first click this is undefined but after the second it returns a value
let resp = this.http.post("https://localhost:8080/api/auth/login", data, httpOptions);
resp.subscribe((response: LoginResponse) => {
if(response) {
this.loginResponse = response
}
});
}
The issue seems to be that after the first click, the post doesn't returns undefined
but after the second it returns a value.
I believe that the issue is that the program isn't waiting for the API to return a value but then I don't understand why after the second click it works.
With Angular 10, does anyone know how to make sure the post
is waited?