【发布时间】:2021-11-21 07:59:50
【问题描述】:
当我重新加载我的页面时,它总是转到空白页面而不是同一页面。这背后的原因是一旦用户刷新页面就会调用 canActivate 方法,该方法正在检查用户的权限,并且无法立即获取用户数据。用户数据会在几秒钟后出现。
我发现我可以在订阅中使用retryWhen,所以调用会重试3次,如果没有完成,我可以调用navigateToNoAccessArea()函数。
功能如下:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
{
return this.getUserData(route);
}
private getUserData(route: ActivatedRouteSnapshot): Observable<boolean> {
return this.userService.getUserData()
.pipe(
map(userData => {
// If userData is empty, it returns an error (and catched in retryWhen)
if(userData === null) throw new Error('User Data not initialized');
return userData;
}),
// when no data is present, it retries the subscription (up to 3 times)
retryWhen(err => err.pipe(delay(1000), take(3),
finalize(()=> {
// this is called after it fails 3 times
// return does not work
this.navigateToNoAccessArea();
return false;
})
)),
map(userData=> {
// this map is called when data is got (if the retry fails 3 times it is skipped)
// ***Some data manipulation is done here and true or false is returned ***
}),
)
}
如果重试失败 3 次,我应该以某种方式返回 false(因此 canActivate() 不会与 EmptyErrorImpl {message: 'no elements in sequence', name: 'EmptyError'} 出错。重定向到无访问区域的工作正常。
【问题讨论】:
标签: angular typescript rxjs angular-ui-router canactivate