Angular 6 Router导航失效求助:Unlock组件内router.navigate无响应
兄弟,我看了你的代码,这个跳转无响应的问题我之前也碰到过,结合你给出的代码,重点排查这几个方向:
1. 先查Dashboard路由的CanActivate守卫逻辑(大概率是这里的问题)
你的AccessGuard里的canActivate方法有个致命的逻辑漏洞:
if (!this.userService.isCpo()) { this.router.navigate(['/unlock']); } return true;
当用户解锁账户后,如果this.userService.isCpo()还是返回false,守卫会触发跳转到/unlock,但最后居然返回true——这会导致重定向死循环:
- 你在Unlock组件里调用
navigate('/dashboard') - Dashboard的守卫检查发现不是Cpo,立刻跳回Unlock
- 但守卫返回了
true,路由器会继续尝试加载Dashboard,又被守卫踢回Unlock - 表面上看起来是跳转没反应,实际上路由器在偷偷循环
验证&修复方法:
- 先在解锁成功的回调里打印
console.log(this.userService.isCpo()),确认解锁后这个值是不是真的变成true了 - 修改守卫逻辑,要重定向的时候必须返回
false,阻止当前路由加载:if (!this.userService.isCpo()) { this.router.navigate(['/unlock']); return false; // 这里一定要返回false,不然路由器会硬着头皮加载Dashboard } return true;
2. 给Router.navigate加错误捕获,揪出隐藏问题
router.navigate()返回的是Promise,哪怕调试器能走到这行,也可能因为路由拦截、配置错误等原因失败,加个catch就能看到具体错误:
this.router.navigate(['/dashboard']) .then(success => console.log('跳转状态:', success)) .catch(err => console.error('跳转失败原因:', err));
这个步骤能帮你快速定位是路由本身的问题,还是守卫的问题。
3. 补全OAuth令牌刷新的错误处理
你现在的代码里oauthService.refreshToken().then(...)没处理失败的情况,如果刷新令牌的时候出错了,虽然你说调试能走到跳转那行,但还是建议加上错误处理,避免后续踩坑:
this.oauthService.refreshToken() .then(done => { // 你的现有逻辑 }) .catch(err => { console.error('令牌刷新失败:', err); this.isLoading = false; this.toastr.error('令牌刷新失败,请重试'); });
4. 重构嵌套的异步逻辑,避免上下文混乱
你现在的代码嵌套了三层异步(subscribe套then再套subscribe),虽然能跑,但很容易出现上下文丢失或者错误遗漏的问题。用RxJS的操作符重构一下,逻辑更清晰:
submit() { if (!this.unlockForm.valid) return; this.isLoading = true; this.userDataService.unlockCpo(this.model) .pipe( // 把Promise转成Observable,方便链式调用 switchMap(() => from(this.oauthService.refreshToken())), switchMap(() => this.translateService.get('UnlockAccount.UnlockSuccess')), // 统一处理整个流程的错误 catchError(err => { console.error('解锁流程出错:', err); this.isLoading = false; this.toastr.error('解锁失败,请重试'); return throwError(() => err); }) ) .subscribe(res => { this.toastr.success(res); this.isLoading = false; this.router.navigate(['/dashboard']) .catch(err => console.error('跳转失败:', err)); }); }
5. 临时屏蔽守卫,验证路由本身是否正常
可以先把Dashboard路由的canActivate注释掉,直接测试router.navigate(['/dashboard'])能不能正常跳转。如果能,那100%是守卫的逻辑问题;如果还是不行,再检查路由配置有没有拼写错误,或者Dashboard组件本身有没有加载失败的情况。
内容的提问来源于stack exchange,提问作者tlq
相关产品推荐
相关产品推荐

