等待组件变量被订阅设置



我必须调用我的组件。第二个取决于第一个调用的结果。在第一次调用时,我为组件变量"锁定"设置了值。第二次调用应该在结果为true时执行——>锁定= true。但是,在第一次调用完成并设置值之前,它将到达代码。我该如何等待代码的执行,直到调用getbyusername;完成。

下面是我的代码:
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."
}
}
}

您可以在第一次调用的回调中检查isLocked变量,这样您就可以确定您收到了答案并且isLocked变量已设置

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."
}
}
}
);
}
}

相关内容

  • 没有找到相关文章

最新更新