I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning locked = true. However, it seems to reach the code before the completion of the first call and setting the value. How can I delay the execution of my code until the call "getByUsernamer" is finished?
Below is the relevant code snippet:
export class LoginComponent implements OnInit {
errorMessage: string = "";
isLocked = false;
username: string | null = "";
constructor(
private authService: AuthService,
private cookieService: CookieService,
private router: Router,
private jwtTokenService: JwtTokenService,
private userService: UserService) {
}
ngOnInit(): void {
}
test() {
this.userService.getUserByUsername(this.username)?.subscribe({
next: response => {
let user: User = response;
this.isLocked = user.locked
}
});
if (!this.isLocked) {
this.router.navigate(['/home']).finally(() => this.userService.setLastLogin(this.username).subscribe());
} else {
this.errorMessage = "The user is locked.";
}
}
}