我希望在API调用成功之前阻止组件加载。 API调用会未经授权返回200或401。如果返回401,将用户重定向到登录页面。
我有解析程序服务
@Injectable()
export class UserDetailResolve implements Resolve<any> {
constructor(private router: Router, private userService: UserService) {
}
resolve() {
return this.userService.verifyUserSession().catch(() => {
this.router.navigate(['auth/sign-in']);
return Observable.empty();
});
}
}
使用解析器进行路由:
{
path: '',
resolve: {
valid: UserDetailResolve,
},
loadChildren: 'app/dashboard/dashboard.module#DashboardModule',
},
如果用户登录并刷新,直到API返回200为止,但如果用户刷新浏览器并且API返回401,则中断(白页,无控制台错误)。
编辑: 我还使用了canActivate:
canActivate() {
return this.authService.isAuthenticated()
.pipe(
tap(authenticated => {
if (!authenticated) {
this.router.navigate(['auth/sign-in']);
} else {
this.userService.verifyUserSession().toPromise().then(res => {
}).catch(error => {
this.router.navigate(['auth/sign-in']);
});
}
}),
);
}
verifyUserSession() {
return this.http.get<any>(API_URL + 'auth/verify-session');
}
但是我得到相同的结果。加载一次后,它会立即显示该组件,并且当用户刷新时,API返回401(会话已过期),导致显示该组件一秒钟然后注销。
答案 0 :(得分:1)
您可以尝试使用此代码吗?
CanRunAsync