出现这种情况的原因可能是异步代码的执行顺序问题,例如在subscribe方法中执行了异步操作,而IF语句是同步执行的。 建议将ELSE语句中的代码放到IF语句内部,以确保在IF语句执行成功后不会执行ELSE语句。以下是代码示例:
this.userService.getUserById(this.userId).subscribe( (user) => { if(user) { this.currentUser = user; console.log('User found'); // 在此处编写成功获取用户的代码 } else { console.log('User not found'); // 将ELSE中的代码移到IF内部 this.router.navigate(['/not-found']); return; } } );
如果您需要在IF语句外部使用ELSE语句中的代码,则建议将其封装在回调函数中,在异步操作完成后再调用。例如:
this.userService.getUserById(this.userId).subscribe( (user) => { if(user) { this.currentUser = user; console.log('User found'); // 在此处编写成功获取用户的代码 this.executeElseCode(); } else { console.log('User not found'); this.executeElseCode(); } } );
executeElseCode() { // 在此处编写ELSE语句中的代码 this.router.navigate(['/not-found']); return; }