我有一个带有 AuthGuard 的 SPA。如果使用未记录页面重定向错误页面,则重定向特定路由。现在。
- 用户未登录
- 呼叫
/dashboard
和Authgurad
重定向/error?returnUrl=/dashboard
- 用户呼叫
/login?key=112233
- 登录页面订阅
AuthService
并创建用户令牌和重定向/dashboard
- 在渲染
/dashboard
触发之前 AuthGuard 和 AuthGurad 让他们一切都很好 /dashboard
正常渲染- 用户想要导航
/claim/search page
- 路由器更改页面 URL 但
router-outlet
不呈现重定向的组件 - 如果用户刷新窗口浏览器页面正常工作,否则SPA不工作
我在步骤 8,9 中的问题
我的路线:
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full',
},
{
path: 'dashboard',
component: DashboardPageComponent,
canActivate: [AuthGuard]
},
{
path: 'claim',
canActivate: [AuthGuard],
children: [{
path: 'search',
component: ClaimSearchPageComponent,
},
{
path: 'detail/:id',
component: ClaimDetailPageComponent,
}]
},
{
path: 'login',
component: LoginPageComponent,
},
{
path: 'error',
component: ErrorPageComponent,
},
{
path: '**',
component: ErrorPageComponent,
}
];
登录页面:
ngOnInit() {
this._returnUrl = this._route.snapshot.queryParams['returnUrl'] || '/';
this._encryptedKey = this._route.snapshot.queryParams['key'];
this._authenticationService.login(this._encryptedKey)
.subscribe(
data => {
this._router.navigate([this._returnUrl]);
});
}
认证服务:
public get isLogged(): boolean {
return !!this.currentUserSubject.value;
}
public login(encryptedKey: string) {
return super.httpPostModel(User, environment.apiService.endPoints.user.login, { key: encryptedKey }).pipe(map(user => {
sessionStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
return user;
}));
}
认证卫士
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this._authenticationService.isLogged) {
return true;
}
this._router.navigate(['/error'], { queryParams: { returnUrl: state.url } });
return false;
}