I have to calls in my component. The secound depends on the result from the first call.At the first call, I set the value for my component variable "locked". The secound call should be executed when the result is true --> locked = true. But it will reach the code, before the first call is finished and the value is set. How can I wait with the execution of my code, until the call "getByUsernamer" is finished.
Here is my code:
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."
}
}
}
CodePudding user response:
You can check the isLocked
variable in the callback of the first call, so you are sure that you received the answer and the isLocked
variable is set
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;
// Moved here the test so it happens only after
// the first request receive the answer
if (!this.isLocked) {
this.router.navigate(['/home']).finally(() => this.userService.setLastLogin(this.username).subscribe());
} else {
this.errorMessage = "The user is locked."
}
}
}
);
}
}
CodePudding user response:
You can use Promises to resolve this issue. here is a link for your reference https://codecraft.tv/courses/angular/es6-typescript/promises/