我有一个带有AuthGuard的SPA。如果未记录使用情况,则页面将重定向错误页面,否则将重定向特定路由。现在。
/dashboard
和Authgurad
重定向/error?returnUrl=/dashboard
/login?key=112233
AuthService
并创建用户令牌并重定向/dashboard
/dashboard
之前触发AuthGuard和AuthGurad可以使它们一切正常/dashboard
正常呈现/claim/search page
router-outlet
未呈现重定向的组件我在第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;
}
答案 0 :(得分:1)
对于无组件路由(没有路由器插座),您可以使用 canActivateChild 而不是 canActivate ,我建议您在其中添加一个ClaimComponent仅内容
<router-outlet></router-outlet>
并将路线更改为
{
path: 'claim',
component: ClaimComponent, // add this
canActivate: [AuthGuard],
children: [{
path: 'search',
component: ClaimSearchPageComponent,
},
{
path: 'detail/:id',
component: ClaimDetailPageComponent,
}]
},
对于缺少组件的路由,canActivateChild在任何子路由被激活之前运行:
{
path: 'claim',
canActivateChild: [AuthGuard],
children: [{
path: 'search',
component: ClaimSearchPageComponent,
},
{
path: 'detail/:id',
component: ClaimDetailPageComponent,
}]
},
答案 1 :(得分:0)
在路由中,您还需要为父组件(声明组件)指定组件属性。
Try this,
{
path: 'claim',
component: ClaimPAgeComponent,
canActivate: [AuthGuard],
children: [{
path: 'search',
component: ClaimSearchPageComponent,
},
{
path: 'detail/:id',
component: ClaimDetailPageComponent,
}]
}