Tengo que llamar a mi componente. El segundo depende del resultado de la primera llamada. En la primera llamada, establecí el valor de mi variable de componente "bloqueado". La segunda llamada debe ejecutarse cuando el resultado sea verdadero --> bloqueado = verdadero. Pero llegará al código, antes de que finalice la primera llamada y se establezca el valor. ¿Cómo puedo esperar con la ejecución de mi código, hasta que finalice la llamada "getByUsernamer"?
Aquí está mi código:
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." } } }Puede verificar la variable isLocked en la devolución de llamada de la primera llamada, por lo que está seguro de que recibió la respuesta y la variable isLocked está configurada
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." } } } ); } }Puede usar Promesas para resolver este problema. aquí hay un enlace para su referencia https://codecraft.tv/courses/angular/es6-typescript/promises/