我有一个按钮,当我单击它时,它会通过 API 调用将用户登录到数据库中,但是代码似乎不会等待响应,直到第二次单击该按钮。
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
}
});
}
问题似乎是在第一次点击后,帖子没有返回undefined,但在第二次点击后它返回了一个值。
我认为问题在于程序没有等待 API 返回值,但是我不明白为什么在第二次单击后它会起作用。
使用 Angular 10,有谁知道如何确保post等待?